知识大全 SignalR与WCF双工模式结合实现服务端数据直推浏览器端
Posted 知
篇首语:大多数人想要改造这个世界,但却罕有人想改造自己。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 SignalR与WCF双工模式结合实现服务端数据直推浏览器端相关的知识,希望对你有一定的参考价值。
SignalR与WCF双工模式结合实现服务端数据直推浏览器端 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!
之前开发基于WinForm监控的软件 服务端基于Wcf实现 里面涉及双工模式 在客户端里面 采用心跳包机制保持与服务端链接 现在有了新需求 需要开发网页版形式 所以怎么保持与服务端链接是重要点 由于数据量比较大 所以不能采用客户端发起请求不断轮询的方式 参考各种资料后 使用SignalR 主要是支持WebSockets通信 并且Hub链接方式解决了realtime 信息交换的功能问题
下图是MSDN关于解释
Hub:提供与连接到 Hub 的 SignalR 连接进行通信的方法
>Global asax
using System;
using System Collections Generic;
using System Linq;
using System Web;
using System Web Security;
using System Web SessionState;
using System Web Routing;
using Microsoft AspNet SignalR;
namespace LMSCitySignalR
public class Global : System Web HttpApplication
protected void Application_Start(object sender EventArgs e)
RouteTable Routes MapHubs();
protected void Session_Start(object sender EventArgs e)
protected void Application_BeginRequest(object sender EventArgs e)
protected void Application_AuthenticateRequest(object sender EventArgs e)
protected void Application_Error(object sender EventArgs e)
protected void Session_End(object sender EventArgs e)
protected void Application_End(object sender EventArgs e)
页面代码
<%@ Page Language= C# AutoEventWireup= true CodeBehind= CityLmsClient aspx cs Inherits= LMSCitySignalR CityLmsClient %>
<meta equiv= X UA Compatible content= IE=edge />
<!DOCTYPE >
< xmlns= >
<head runat= server >
<meta equiv= Content Type content= text/; charset=utf />
<title>LH CityLMS Client</title>
</head>
<body>
<div id= dvMsg ></div>
Client Mac Address:
<input id= txtMac type= text value= :E : :DA: C:D />
<input id= btnCnLmsSvr type= button value= Connect CityLms Server />
<br>
User Name:<input id= txtUserName type= text value= admin />
User Password:<input id= txtUserPassword type= password value= admin />
<input id= btnLogin type= button value= Login />
<br>
<input id= btnMonitorClientChanel type= button value= MonitorClientChanel />
<br />
<input id= btnEmergencyControl type= button value= Emergency Control />
<br />
<input id= btnDisConSvr type= button value= DisConnect Svr />
<script src= Scripts/jquery js type= text/javascript ></script>
<script src= Scripts/json js type= text/javascript ></script>
<script src= Scripts/jquery signalR js type= text/javascript ></script>
<script src= /signalr/hubs type= text/javascript ></script>
<script type= text/javascript >
$(function ()
/*
* 参考链接:
*· Persistent Connection(HTTP持久链接) 持久性连接 用来解决长时间连接的能力 而且还可以由客户端主动向服务器要求数据 而服务器端也不需要实现太多细节 只需要处理 PersistentConnection 内所提供的五个事件 OnConnected OnReconnected OnReceived OnError 和 OnDisconnect 即可
*· Hub 信息交换器 用来解决 realtime 信息交换的功能 服务器端可以利用 URL 来注册一个或多个 Hub 只要连接到这个 Hub 就能与所有的客户端共享发送到服务器上的信息 同时服务器端可以调用客户端的脚本 不过它背后还是不离 HTTP 的标准 所以它看起来神奇 但它并没有那么神奇 只是 JavaScript 更强 强到可以用像 eval() 或是动态解释执行的方式 允许 JavaScript 能够动态的加载与执行方法调用而己
*/
/*链接对应server端Hub对象*/
var cityLmsClient = nnection cityLmsClientHub;
citytServerResult = function (name message)
$( #dvMsg ) append( <li><strong> + (new Date()) toLocaleTimeString() + Client Mac Address + name
+ Connect CityLms Server Result: + message + </strong></li> );
;
/*断开连接消息提示*/
cityLmsClient client disConSvr = function (message)
alert(message);
;
/*操作消息提示*/
cityLmsClient client operateMsg = function (message)
$( #dvMsg ) append( <li><strong> + (new Date()) toLocaleTimeString() + + message + </strong></li> );
;
nnection hub start() done(function ()
/*链接wcf Server*/
$( #btnCnLmsSvr ) click(function ()
citynServer($( #txtMac ) val());
);
/*应急操作*/
$( #btnEmergencyControl ) click(function ()
cityLmsClient server emergencyControl();
);
/*用户登录*/
$( #btnLogin ) click(function ()
cityLmsClient server userLogin($( #txtUserName ) val() $( #txtUserPassword ) val());
);
/*启动心跳包 以保持与wcf Server连接*/
$( #btnMonitorClientChanel ) click(function ()
cityLmsClient server monitorClientChanel();
);
/*断开连接*/
$( #btnDisConSvr ) click(function ()
cityLmsClient server disConnectSvr();
);
);
/*日志显示*/
nnection hub logging = true;
);
</script>
</body>
</>
cityLmsClientHub cs代码
using System;
using System Collections Generic;
using System Diagnostics;
using System Linq;
using System Reflection;
using System ServiceModel;
using System Threading;
using System Web;
using DL_LMS_Server Default Shared;
using DL_LMS_Server Service DataModel Parameter;
using DL_LMS_Server Service DataModel Result;
using Microsoft AspNet SignalR;
namespace LMSCitySignalR
public class cityLmsClientHub : Hub
ServiceCallBack serCallBack = null;
/// <summary>
/// 应急操作回调
/// </summary>
/// <param name= sender ></param>
/// <param name= e ></param>
private void RealTimeCabChCallBackMessage_Event(object sender LMSClientNotifiedEventArgs e)
COptRealTimeCabChResult optCabChresult = e NotifiedMessage as COptRealTimeCabChResult;
string _sMsg = string Format( CabID: byCh ActType: byCh ActType: byCh ActType: byCh ActType: byCh ActType: byCh ActType: CtuLockStatus:
DateTime Now ToShortTimeString()
optCabChresult CabID
optCabChresult byCh ActType
optCabChresult byCh ActType
optCabChresult byCh ActType
optCabChresult byCh ActType
optCabChresult byCh ActType
optCabChresult byCh ActType
optCabChresult CtuLockStatus);
Clients Client(Context ConnectionId) OperateMsg(_sMsg);
Clients Client(Context ConnectionId) OperateMsg( ==========================end====================== );
public void Hello()
Clients All hello();
private static bool bIsConnect = false;
private static string sMacAddress = null;
private static string sUserName = null;
private static string sUserPassword = null;
/// <summary>
///链接wcf Server
/// </summary>
/// <param name= clientMacAddress >mac地址</param>
/// <returns></returns>
private CommunResult ConnService(string clientMacAddress)
CommunResult result = new CommunResult();
try
SvrRetMessage svrMessage = ClientComServiceFactory GetClientServiceFactory GetClientComService Connect(clientMacAddress);
if (!svrMessage ExcuResult)
result Message = svrMessage Message;
result CommunState = CommState NoRegister;
result CommunState = CommState Scuess;
result Message = 连接成功 ;
catch (EndpointNotFoundException e)
string mes = e Message;
result CommunState = CommState Failed;
result Message = CommMessage sNoServer;
catch (TimeoutException e)
string mes = e Message;
result CommunState = CommState TimeOut;
result Message = CommMessage sTimeOuteMessahe;
catch (Exception e)
string mes = e Message;
result CommunState = CommState Failed;
result Message = CommMessage sNoServer;
return result;
/// <summary>
/// 断开与wcf Server链接
/// </summary>
public void DisConnectSvr()
string _sDisConSvrMsg = string Format( sMacAddress DisConnService() Message);
Clients Client(Context ConnectionId) DisConSvr(_sDisConSvrMsg);
Debug Write(_sDisConSvrMsg);
/// <summary>
/// 客户端与服务器端断开连接
/// </summary>
/// <returns></returns>
private CommunResult DisConnService()
CommunResult result = new CommunResult();
try
ClientComServiceFactory GetClientServiceFactory GetClientComService DisConnect(sMacAddress);
result CommunState = CommState Scuess;
result Message = 断开连接成功 ;
catch (EndpointNotFoundException e)
string mes = e Message;
result CommunState = CommState Failed;
result Message = CommMessage sNoServer;
catch (TimeoutException e)
string mes = e Message;
result CommunState = CommState TimeOut;
result Message = CommMessage sTimeOuteMessahe;
catch (Exception e)
string mes = e Message;
result CommunState = CommState Failed;
result Message = CommMessage sNoServer;
return result;
/// <summary>
/// 心跳包 保持与wcf server链接
/// </summary>
public void MonitorClientChanel()
if (string IsNullOrEmpty(sUserPassword) || string IsNullOrEmpty(sUserName))
return;
ThreadPool QueueUserWorkItem
(
delegate
while (true)
Thread Sleep( );
try
Debug WriteLine(string Format( Client ID: Context ConnectionId DateTime Now));
if (ClientComServiceFactory GetClientServiceFactory getObjetcStatus State == CommunicationState Faulted)
ClientComServiceFactory GetClientServiceFactory getObjetcStatus Abort();
ClientComServiceFactory GetClientServiceFactory GetNewClientComService();
ClientComServiceFactory GetClientServiceFactory GetClientComService ReConnect(sMacAddress sUserName sUserPassword);
catch (Exception ex)
ClientComServiceFactory GetClientServiceFactory GetNewClientComService();
Debug WriteLine(string Format( Time: Exception: Type: DateTime Now ToString( HH:mm:ss ) ex Message ToString() this GetType() ToString()));
);
/// <summary>
/// 链接wcf Server
/// </summary>
/// <param name= clientMacAddress >Mac地址</param>
public void ConServer(string clientMacAddress)
//DebugerHelper dHelper = new DebugerHelper(DebugParameter ObtainCalledMethod);
//dHelper FormartDebuger( Test );
CommunResult _Status = ConnService(clientMacAddress);
//FormartDebuger(MethodBase GetCurrentMethod() hello );
Clients Client(Context ConnectionId) CntServerResult(clientMacAddress _Status Message);
if (_Status CommunState == CommState Scuess)
sMacAddress = clientMacAddress;
bIsConnect = true;
/// <summary>
/// 用户登录
/// </summary>
/// <param name= sName >用户名称</param>
/// <param name= sPassWord >用户密码</param>
public void UserLogin(string sName string sPassWord)
if (CheckConnectStatus())
LoginResult _serverLoginResult = ClientComServiceFactory GetClientServiceFactory GetClientComService UserLogin(sMacAddress sName sPassWord);
if (_serverLoginResult UserLoginStatus == LoginStatus scuess)
sUserName = sName;
sUserPassword = sPassWord;
ServiceCallBack RealTimeCabChCallBack += RealTimeCabChCallBackMessage_Event;
Clients Client(Context ConnectionId) OperateMsg(string Format( 用户: 登录 sName _serverLoginResult UserLoginStatus == LoginStatus scuess ? 成功 : 失败 原因: + _serverLoginResult LoginMessage));
/// <summary>
/// 应急操作
/// </summary>
public void EmergencyControl()
if (CheckConnectStatus())
OptRealCtuChannelParameter parameter = new OptRealCtuChannelParameter();
parameter byCh ActType = ;
parameter byCh ActType = ;
parameter byCh ActType = ;
parameter byCh ActType = ;
parameter byCh ActType = ;
parameter byCh ActType = ;
parameter CabID = afa b c c bf b cf c fbfa ;
parameter ClientMacAddress = sMacAddress;
parameter OptTimeOut = ;
parameter OptRealDateTime = DateTime Now;
parameter RealTimeStatus = ;
SvrRetMessage returnMessage = ClientComServiceFactory GetClientServiceFactory GetClientComService SendOptRealTimeCtuChMessage(parameter sMacAddress);
Clients Client(Context ConnectionId) OperateMsg(string Format( CabID: 应急控制 操作: parameter CabID returnMessage ExcuResult == true ? 成功 : 失败 原因: + returnMessage Message));
/// <summary>
/// 检查是否已经连接wcf Server
/// </summary>
/// <returns></returns>
private bool CheckConnectStatus()
if (bIsConnect && !string IsNullOrEmpty(sMacAddress))
return true;
else
Clients Client(Context ConnectionId) OperateMsg( 当前还未连接CityLms Server );
return false;
实现效果
>> cha138/Article/program/net/201311/12646相关参考
网络适配器的连接速度和双工模式怎么调网速最快连接速度和双式模型里面,改成全双工100M的那个还有就是打开QOS数据包里面受限的20%带宽:(“开始”→“运行”中输入gpedit.msc(扩展名一定不能
知识大全 各位老师,为何在路由器中设置自动拨号模式就是签约网速,而选择100兆全双工就慢了。10兆半双工就更慢
各位老师,为何在路由器中设置自动拨号模式就是签约网速,而选择100兆全双工就慢了。10兆半双工就更慢家庭网络环境布线:1、有电信猫:电信猫----路由器wan口;路由器lan口----电脑;2、没得电
Java网络编程从入门到精通(26):在服务端接收和发送数据 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看
知识大全 服务端拼接json数据格式的正确写法(Append方式)
服务端拼接json数据格式的正确写法(Append方式) 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下
知识大全 jQuery DataTables插件从服务器端获取数据的方法
jQueryDataTables插件从服务器端获取数据的方法 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看
正常的数据库连接字符串配置这是在MSSQL服务器端口是(默认)的情况下<addkey=Articlevalue=server=;uid=Admin;pwd=admin;database=db
ajax调用WCF服务 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! 关于AJAX调用WCF服务
什么是半双工,什么是全双工,请详细解释一下全双工(FullDuplex)是指在发送数据的同时也能够接收数据,两者同步进行,这好像我们平时打电话一样,说话的同时也能够听到对方的声音。目前的网卡一般都支持
一起学WCF--消息通信模式 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! 这一节大家共同研究下
Oracle数据导入导出imp/exp就相当于oracle数据还原与备份exp命令可以把数据从远程数据库服务器导出到本地的dmp文件imp命令可以把dmp文件从本地导入到远处的数据库服务器中利用这