Using WebSockets with ASP.NET Web API

后端 未结 5 1467
眼角桃花
眼角桃花 2020-12-02 14:52

What is the preferred method for using raw websockets in an ASP.NET Web API application?

We\'d like to use binary WebSockets on a couple of our inte

5条回答
  •  既然无缘
    2020-12-02 15:18

    I found this example:

    Sample code (reproduced from the post):

    public class WSHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.IsWebSocketRequest)
            {
                context.AcceptWebSocketRequest(ProcessWSChat);
            }
        }
    
        public bool IsReusable { get { return false; } }
    
        private async Task ProcessWSChat(AspNetWebSocketContext context)
        {
            WebSocket socket = context.WebSocket;
            while (true)
            {
                ArraySegment buffer = new ArraySegment(new byte[1024]);
                WebSocketReceiveResult result = await socket.ReceiveAsync(
                    buffer, CancellationToken.None);
                if (socket.State == WebSocketState.Open)
                {
                    string userMessage = Encoding.UTF8.GetString(
                        buffer.Array, 0, result.Count);
                    userMessage = "You sent: " + userMessage + " at " + 
                        DateTime.Now.ToLongTimeString();
                    buffer = new ArraySegment(
                        Encoding.UTF8.GetBytes(userMessage));
                    await socket.SendAsync(
                        buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                else
                {
                    break;
                }
            }
        }
    }
    

提交回复
热议问题