C#实现WebSocket协议客户端和服务器websocket sharp组件实例解析

2019-12-30 17:10:24于海丽

    2.WebSocket.CloseAsync():


public void CloseAsync (CloseStatusCode code, string reason)
  {
   string msg;
   if (!CheckParametersForClose (code, reason, _client, out msg)) {
    _logger.Error (msg);
    error ("An error has occurred in closing the connection.", null);
    return;
   }
   closeAsync ((ushort) code, reason);
  }

    该方法以指定的方式异步关闭WebSocket连接,该方法接受两个参数,CloseStatusCode表示关闭原因的状态码,该参数是一个枚举类型。reason表示关闭的原因。大小必须是123字节或更少。if (!CheckParametersForClose (code, reason, _client, out msg))检查参数关闭。

    3.WebSocket.createHandshakeRequest():


private HttpRequest createHandshakeRequest()
    {
      var ret = HttpRequest.CreateWebSocketRequest(_uri);
      var headers = ret.Headers;
      if (!_origin.IsNullOrEmpty())
        headers["Origin"] = _origin;
      headers["Sec-WebSocket-Key"] = _base64Key;
      _protocolsRequested = _protocols != null;
      if (_protocolsRequested)
        headers["Sec-WebSocket-Protocol"] = _protocols.ToString(", ");
      _extensionsRequested = _compression != CompressionMethod.None;
      if (_extensionsRequested)
        headers["Sec-WebSocket-Extensions"] = createExtensions();
      headers["Sec-WebSocket-Version"] = _version;
      AuthenticationResponse authRes = null;
      if (_authChallenge != null && _credentials != null)
      {
        authRes = new AuthenticationResponse(_authChallenge, _credentials, _nonceCount);
        _nonceCount = authRes.NonceCount;
      }
      else if (_preAuth)
      {
        authRes = new AuthenticationResponse(_credentials);
      }
      if (authRes != null)
        headers["Authorization"] = authRes.ToString();
      if (_cookies.Count > 0)
        ret.SetCookies(_cookies);
      return ret;
    }

     该方法用于客户端创建一个websocket请求,创建握手请求。var ret = HttpRequest.CreateWebSocketRequest(_uri);根据传入的uri调用HttpRequest的方法创建请求。该方法主要操作http头部信息,创建请求。

四.总结

   对于这个组件,个人感觉还是有一些用,这个组件很好的实现了websocket,这里也只是简单的介绍,需要使用的同学,可以自取,因为该组件是开源的,所以一些实际情况中可以自行修改源码,达到最大限度的扩展性。在项目的技术选择中,个人比较主张开源免费的框架和组件,不仅是项目预算的问题,更有方便扩展的作用。

以上所述是小编给大家介绍的C#实现WebSocket协议客户端和服务器websocket-sharp组件实例解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ASPKU网站的支持!