熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

SignalR與WCF雙工模式結合實現服務端數據直推浏覽器端

2022-06-13   來源: .NET編程 

  之前開發基於WinForm監控的軟件服務端基於Wcf實現裡面涉及雙工模式在客戶端裡面采用心跳包機制保持與服務端鏈接現在有了新需求需要開發網頁版形式所以怎麼保持與服務端鏈接是重要點由於數據量比較大所以不能采用客戶端發起請求不斷輪詢的方式參考各種資料後使用SignalR主要是支持WebSockets通信並且Hub鏈接方式解決了realtime 信息交換的功能問題

  下圖是MSDN關於解釋

  Hub:提供與連接到 Hub 的 SignalR 連接進行通信的方法

image

  Globalasax

  using System;

  using SystemCollectionsGeneric;

  using SystemLinq;

  using SystemWeb;

  using SystemWebSecurity;

  using SystemWebSessionState;

  using SystemWebRouting;

  using MicrosoftAspNetSignalR;

  namespace LMSCitySignalR

  {

  public class Global : SystemWebHttpApplication

  {

  protected void Application_Start(object sender EventArgs e)

  {

  RouteTableRoutesMapHubs();

  }

  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=CityLmsClientaspxcs Inherits=LMSCitySignalRCityLmsClient %>

  <meta httpequiv=XUACompatible content=IE=edge />

  <!DOCTYPE html>

  <html xmlns=>

  <head runat=server>

  <meta httpequiv=ContentType content=text/html; 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/jqueryjs type=text/javascript></script>

  <script src=Scripts/jsonjs type=text/javascript></script>

  <script src=Scripts/jquerysignalRjs 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 = nnectioncityLmsClientHub;

  citytServerResult = function (name message) {

  $(#dvMsg)append(<li><strong> + (new Date())toLocaleTimeString() + Client Mac Address + name

  +    Connect CityLms Server Result: + message + </strong></li>);

  };

  /*斷開連接消息提示*/

  cityLmsClientclientdisConSvr = function (message) {

  alert(message);

  };

  /*操作消息提示*/

  cityLmsClientclientoperateMsg = function (message) {

  $(#dvMsg)append(<li><strong> + (new Date())toLocaleTimeString() + + message + </strong></li>);

  };

  nnectionhubstart()done(function () {

  /*鏈接wcf Server*/

  $(#btnCnLmsSvr)click(function () {

  citynServer($(#txtMac)val());

  });

  /*應急操作*/

  $(#btnEmergencyControl)click(function () {

  cityLmsClientserveremergencyControl();

  });

  /*用戶登錄*/

  $(#btnLogin)click(function () {

  cityLmsClientserveruserLogin($(#txtUserName)val() $(#txtUserPassword)val());

  });

  /*啟動心跳包以保持與wcf Server連接*/

  $(#btnMonitorClientChanel)click(function () {

  cityLmsClientservermonitorClientChanel();

  });

  /*斷開連接*/

  $(#btnDisConSvr)click(function () {

  cityLmsClientserverdisConnectSvr();

  });

  });

  /*日志顯示*/

  nnectionhublogging = true;

  });

  </script>

  </body>

  </html>

  cityLmsClientHubcs代碼

  using System;

  using SystemCollectionsGeneric;

  using SystemDiagnostics;

  using SystemLinq;

  using SystemReflection;

  using SystemServiceModel;

  using SystemThreading;

  using SystemWeb;

  using DL_LMS_ServerDefaultShared;

  using DL_LMS_ServerServiceDataModelParameter;

  using DL_LMS_ServerServiceDataModelResult;

  using MicrosoftAspNetSignalR;

  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 = eNotifiedMessage as COptRealTimeCabChResult;

  string _sMsg = stringFormat({}CabID:{}byChActType:{}byChActType:{}byChActType:{}byChActType:{}byChActType:{}byChActType:{}CtuLockStatus:{}

  DateTimeNowToShortTimeString()

  optCabChresultCabID

  optCabChresultbyChActType

  optCabChresultbyChActType

  optCabChresultbyChActType

  optCabChresultbyChActType

  optCabChresultbyChActType

  optCabChresultbyChActType

  optCabChresultCtuLockStatus);

  ClientsClient(ContextConnectionId)OperateMsg(_sMsg);

  ClientsClient(ContextConnectionId)OperateMsg(==========================end======================);

  }

  public void Hello()

  {

  ClientsAllhello();

  }

  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 = ClientComServiceFactoryGetClientServiceFactoryGetClientComServiceConnect(clientMacAddress);

  if (!svrMessageExcuResult)

  {

  resultMessage = svrMessageMessage;

  resultCommunState = CommStateNoRegister;

  }

  resultCommunState = CommStateScuess;

  resultMessage = 連接成功;

  }

  catch (EndpointNotFoundException e)

  {

  string mes = eMessage;

  resultCommunState = CommStateFailed;

  resultMessage = CommMessagesNoServer;

  }

  catch (TimeoutException e)

  {

  string mes = eMessage;

  resultCommunState = CommStateTimeOut;

  resultMessage = CommMessagesTimeOuteMessahe;

  }

  catch (Exception e)

  {

  string mes = eMessage;

  resultCommunState = CommStateFailed;

  resultMessage = CommMessagesNoServer;

  }

  return result;

  }

  /// <summary>

  /// 斷開與wcf Server鏈接

  /// </summary>

  public void DisConnectSvr()

  {

  string _sDisConSvrMsg = stringFormat({}{} sMacAddress DisConnService()Message);

  ClientsClient(ContextConnectionId)DisConSvr(_sDisConSvrMsg);

  DebugWrite(_sDisConSvrMsg);

  }

  /// <summary>

  /// 客戶端與服務器端斷開連接

  /// </summary>

  /// <returns></returns>

  private CommunResult DisConnService()

  {

  CommunResult result = new CommunResult();

  try

  {

  ClientComServiceFactoryGetClientServiceFactoryGetClientComServiceDisConnect(sMacAddress);

  resultCommunState = CommStateScuess;

  resultMessage = 斷開連接成功;

  }

  catch (EndpointNotFoundException e)

  {

  string mes = eMessage;

  resultCommunState = CommStateFailed;

  resultMessage = CommMessagesNoServer;

  }

  catch (TimeoutException e)

  {

  string mes = eMessage;

  resultCommunState = CommStateTimeOut;

  resultMessage = CommMessagesTimeOuteMessahe;

  }

  catch (Exception e)

  {

  string mes = eMessage;

  resultCommunState = CommStateFailed;

  resultMessage = CommMessagesNoServer;

  }

  return result;

  }

  /// <summary>

  /// 心跳包保持與wcf server鏈接

  /// </summary>

  public void MonitorClientChanel()

  {

  if (stringIsNullOrEmpty(sUserPassword) || stringIsNullOrEmpty(sUserName))

  return;

  ThreadPoolQueueUserWorkItem

  (

  delegate

  {

  while (true)

  {

  ThreadSleep();

  try

  {

  DebugWriteLine(stringFormat({}Client ID:{} ContextConnectionId DateTimeNow));

  if (ClientComServiceFactoryGetClientServiceFactorygetObjetcStatusState == CommunicationStateFaulted)

  {

  ClientComServiceFactoryGetClientServiceFactorygetObjetcStatusAbort();

  ClientComServiceFactoryGetClientServiceFactoryGetNewClientComService();

  }

  ClientComServiceFactoryGetClientServiceFactoryGetClientComServiceReConnect(sMacAddress sUserName sUserPassword);

  }

  catch (Exception ex)

  {

  ClientComServiceFactoryGetClientServiceFactoryGetNewClientComService();

  DebugWriteLine(stringFormat(Time:{}Exception:{}Type:{} DateTimeNowToString(HH:mm:ss) exMessageToString() thisGetType()ToString()));

  }

  }

  }

  );

  }

  /// <summary>

  /// 鏈接wcf Server

  /// </summary>

  /// <param name=clientMacAddress>Mac地址</param>

  public void ConServer(string clientMacAddress)

  {

  //DebugerHelper dHelper = new DebugerHelper(DebugParameterObtainCalledMethod);

  //dHelperFormartDebuger(Test);

  CommunResult _comStatus = ConnService(clientMacAddress);

  //FormartDebuger(MethodBaseGetCurrentMethod() hello);

  ClientsClient(ContextConnectionId)CntServerResult(clientMacAddress _comStatusMessage);

  if (_comStatusCommunState == CommStateScuess)

  {

  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 = ClientComServiceFactoryGetClientServiceFactoryGetClientComServiceUserLogin(sMacAddress sName sPassWord);

  if (_serverLoginResultUserLoginStatus == LoginStatusscuess)

  {

  sUserName = sName;

  sUserPassword = sPassWord;

  ServiceCallBackRealTimeCabChCallBack += RealTimeCabChCallBackMessage_Event;

  }

  ClientsClient(ContextConnectionId)OperateMsg(stringFormat(用戶:{}登錄{} sName _serverLoginResultUserLoginStatus == LoginStatusscuess ? 成功 : 失敗原因: + _serverLoginResultLoginMessage));

  }

  }

  /// <summary>

  /// 應急操作

  /// </summary>

  public void EmergencyControl()

  {

  if (CheckConnectStatus())

  {

  OptRealCtuChannelParameter parameter = new OptRealCtuChannelParameter();

  parameterbyChActType = ;

  parameterbyChActType = ;

  parameterbyChActType = ;

  parameterbyChActType = ;

  parameterbyChActType = ;

  parameterbyChActType = ;

  parameterCabID = afabccbfbcfcfbfa;

  parameterClientMacAddress = sMacAddress;

  parameterOptTimeOut = ;

  parameterOptRealDateTime = DateTimeNow;

  parameterRealTimeStatus = ;

  SvrRetMessage returnMessage = ClientComServiceFactoryGetClientServiceFactoryGetClientComServiceSendOptRealTimeCtuChMessage(parameter sMacAddress);

  ClientsClient(ContextConnectionId)OperateMsg(stringFormat(CabID:{}應急控制操作:{} parameterCabID returnMessageExcuResult == true ? 成功 : 失敗原因: + returnMessageMessage));

  }

  }

  /// <summary>

  /// 檢查是否已經連接wcf Server

  /// </summary>

  /// <returns></returns>

  private bool CheckConnectStatus()

  {

  if (bIsConnect && !stringIsNullOrEmpty(sMacAddress))

  return true;

  else

  ClientsClient(ContextConnectionId)OperateMsg(當前還未連接CityLms Server);

  return false;

  }

  }

  }

  實現效果

image
image

  才疏學淺如有錯誤敬請指出


From:http://tw.wingwit.com/Article/program/net/201311/12646.html
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.