欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WebSocket简单尝试

程序员文章站 2022-04-02 08:38:03
System.Net.WebSockets.WebSocket 需要.NET 4.5,IIS8以上,Windows Server2008R2自带的IIS不支持,Windows8及Server2012以上自带的IIS可以 1、实现IHttpHandler用于处理webSocket请求 2、在web.C ......

System.Net.WebSockets.WebSocket

需要.NET 4.5,IIS8以上,Windows Server2008R2自带的IIS不支持,Windows8及Server2012以上自带的IIS可以

1、实现IHttpHandler用于处理webSocket请求

using System;
using System.Net.WebSockets;
using System.Threading.Tasks;
using System.Web;
using System.Web.WebSockets;

namespace WebSocketTest
{
    public class MyWebSocketHandler : IHttpHandler
    {
        /// <summary>
        /// 设置实例不可以重复使用
        /// </summary>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 判断是否是WebSocket请求
        /// 是交由handlerWebSocketAsync方法处理
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            if (context.IsWebSocketRequest)
            {
                context.AcceptWebSocketRequest(handlerWebSocketAsync);
            }
        }

        private async Task handlerWebSocketAsync(AspNetWebSocketContext context)
        {
            WebSocket webSocket = context.WebSocket;

            await webSocket.SendMsgAsync("连接成功");

            while (true)
            {
                if (webSocket.State == WebSocketState.Open)
                {
                    string msg = await webSocket.ReceiveMsgAsync();
                    webSocket.SendMsgAsync(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        + @",Receive:" + msg);
                }
            }
        }
    }
}
webSocket.ReceiveMsgAsync 和 webSocket.SendMsgAsync 是我自己封装的两个扩展方法,用于字符串和byte[]转换
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebSocketTest
{
    public static class WebSocketHelper
    {
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="webSocket"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static async Task SendMsgAsync(this WebSocket webSocket, string msg)
        {
            byte[] bytesMsg = Encoding.UTF8.GetBytes(msg);
            ArraySegment<byte> segment = new ArraySegment<byte>(bytesMsg);
            await webSocket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="webSocket"></param>
        /// <returns></returns>
        public static async Task<string> ReceiveMsgAsync(this WebSocket webSocket)
        {
            ArraySegment<byte> receiveSegment = new ArraySegment<byte>(new byte[1024]);
            WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(receiveSegment, CancellationToken.None);

            string clientMsg = Encoding.UTF8.GetString(receiveSegment.Array, 0, receiveResult.Count);
            return clientMsg;
        }
    }
}

 

2、在web.Config中加入自定义的handler,集成模式需要在<system.webServer>节点配置,经典模式在<system.web>节点配置

<system.web>
    <compilation debug="true" targetFramework="4.6.1"/>
    <httpRuntime targetFramework="4.5"/>
    <!--<httpHandlers>
      <add verb="*" path="*" type="WebSocketTest.MyWebSocketHandler, WebSocketTest" />
    </httpHandlers>-->
  </system.web>
  <system.webServer>
    <handlers>
      <add name="webSocketHandler" verb="*" path="*" type="WebSocketTest.MyWebSocketHandler, WebSocketTest"/>
    </handlers>
  </system.webServer>

3、运行VS,进行测试

WebSocket简单尝试

运行结果

WebSocket简单尝试