Websocket c#listener as a service

时间:2017-03-14 11:03:06

标签: c# service websocket

我正在考虑设置一个服务,该服务将侦听从多个websocket服务器收到的消息,并最终在没有前端的现有应用程序中启动其他业务逻辑。

作为对websockets完全陌生的人,我不确定是实现此问题的最佳方式。

有没有人有任何类似的经验?

2 个答案:

答案 0 :(得分:1)

你需要一个很好的教程。

检查this使用在c#中使用websocket的SignalR的人。{/ p>

答案 1 :(得分:1)

如果您使用的是IIS,则可以使用System.Web.WebSockets.AspNetWebSocketContext通过WebSocket处理IHttpHandler个连接,示例:

/// <summary>
/// Called when a new web socket connection has been established.
/// </summary>
/// <param name="webSocketContext">The web socket context.</param>
public abstract void WebSocketContext(System.Web.WebSockets.AspNetWebSocketContext webSocketContext);

/// <summary>
/// Process request method.
/// </summary>
/// <param name="context">The current http context.</param>
public void ProcessRequest(System.Web.HttpContext context)
{
    HttpResponse response = null;

    // Get the request and response context.
    response = context.Response;

    // If the request is a web socket protocol
    if (context.IsWebSocketRequest)
    {
         // Process the request.
         ProcessWebSocketRequest(context);
    }
}

/// <summary>
/// Process the request.
/// </summary>
/// <param name="httpContext">The http context.</param>
private void ProcessWebSocketRequest(System.Web.HttpContext httpContext)
{
     HttpResponse response = null;

     // Get the request and response context.
     response = httpContext.Response;

     // Process the request asynchronously.
     httpContext.AcceptWebSocketRequest(ProcessWebSocketRequestAsync);
}

/// <summary>
/// Process the request asynchronously.
/// </summary>
/// <param name="webSocketContext">The web socket context.</param>
/// <returns>The task to execute.</returns>
private async Task ProcessWebSocketRequestAsync(System.Web.WebSockets.AspNetWebSocketContext webSocketContext)
{
     await Nequeo.Threading.AsyncOperationResult<bool>.
         RunTask(() =>
         {
             // Process the request.
             WebSocketContext(webSocketContext);
         });
}

如果您使用的是独立服务器(可以将其作为Windows服务实现),那么您可以使用System.Net.WebSockets.HttpListenerWebSocketContext通过HttpListenerContext来处理“WebSocket”连接,示例:

/// <summary>
/// The on web socket context event handler, triggered when a new connection is established or data is present. Should be used when implementing a new connection.
/// </summary>
public event Nequeo.Threading.EventHandler<System.Net.WebSockets.HttpListenerWebSocketContext> OnWebSocketContext;

/// <summary>
/// On http context action handler.
/// </summary>
/// <param name="context">The current http context.</param>
private void OnHttpContextHandler(HttpListenerContext context)
{
     HttpListenerRequest request = null;
     HttpListenerResponse response = null;

     // Get the request and response context.
     request = context.Request;
     response = context.Response;

     // If the request is a web socket protocol
     if (request.IsWebSocketRequest)
     {
          // Process the web socket request.
          ProcessWebSocketRequest(context);
     }
}

/// <summary>
/// Process the web socket protocol request.
/// </summary>
/// <param name="context">The current http context.</param>
private async void ProcessWebSocketRequest(HttpListenerContext context)
{
     HttpListenerResponse response = null;

     // Get the request and response context.
     response = context.Response;

     // When calling `AcceptWebSocketAsync` the negotiated subprotocol 
     // must be specified. This sample assumes that no subprotocol  was requested. 
     HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(subProtocol: null);

     // Send the web socket to the handler.
     if (OnWebSocketContext != null)
          OnWebSocketContext(this, webSocketContext);
}

收到请求后,您将开始对话,示例。

/// <summary>
/// On WebSocket context.
/// </summary>
/// <param name="context"></param>
private async void OnWebSocketContext(System.Net.WebSockets.HttpListenerWebSocketContext context)
{    
     WebSocket webSocket = null;

     try
     {
         // Get the current web socket.
         webSocket = context.WebSocket;

         CancellationTokenSource receiveCancelToken = new CancellationTokenSource();
         byte[] receiveBuffer = new byte[READ_BUFFER_SIZE];

         // While the WebSocket connection remains open run a 
         // simple loop that receives data and sends it back.
         while (webSocket.State == WebSocketState.Open)
         {
             // Receive the next set of data.
             ArraySegment<byte> arrayBuffer = new ArraySegment<byte>(receiveBuffer);
             WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(arrayBuffer, receiveCancelToken.Token);

             // If the connection has been closed.
             if (receiveResult.MessageType == WebSocketMessageType.Close)
             {
                  break;
             }
             else
             {
                  // Start conversation.
             }
        }

        // Cancel the receive request.
        if (webSocket.State != WebSocketState.Open)
             receiveCancelToken.Cancel();
    }
    catch { }
    finally
    {
        // Clean up by disposing the WebSocket.
        if (webSocket != null)
            webSocket.Dispose();
    }
}