websocket简易demo

websocket可以通过长连接通信,类似于socket

今天实现一个最简单的demo,记录一下

参考文档 https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/websockets?view=aspnetcore-3.1

环境

win10 / vs2019 / .net core 3.1

建立项目

1.建立.net core的控制台项目

2.添加nuget包

  // .net core kestrel服务器

  Microsoft.AspNetCore.Server.Kestrel 

  // websocket 包,.net core自家的

       Microsoft.AspNetCore.WebSockets

  // 配置工具,不是必须

  Microsoft.Extensions.Configuration.Json

3.添加文件

  kestrel.json // 设置kestrel服务器监听端口

{
  "server.urls": "http://localhost:10800;http://*:10800"
}

4.Program.cs  main方法修改

        static void Main(string[] args)
        {
            
            // kestrel服务器配置文件载入
            IConfiguration kestrelCfg = new ConfigurationBuilder()
                .AddJsonFile("kestrel.json")
                .Build();

            // websocket配置文件
            var webSocketCfg = new WebSocketOptions()
            {
                // 向客户端发送“ping”帧的频率,以确保代理保持连接处于打开状态。.默认值为 2 分钟.
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                // 用于接收数据的缓冲区的大小.高级用户可能需要对其进行更改,以便根据数据大小调整性能.默认值为4 KB.
                ReceiveBufferSize = 4 * 1024
            };

相比http连接,websocket建立连接后,可以主动向客户端发送消息.为了验证这一点,在服务端做了一个定时器

当websocket建立连接后,定时向客户端发送当前时间

t = new System.Timers.Timer
{
    Interval = 2000
};
t.Elapsed += T_Elapsed;
t.Start();
        private static void T_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            
                WebSocket webSocket = connDict[1];
                byte[] rebuffer = System.Text.Encoding.UTF8.GetBytes("服务器报时: " + DateTimeOffset.Now.ToString());
                ArraySegment<byte> re = new ArraySegment<byte>(rebuffer, 0, rebuffer.Length);

                webSocket.SendAsync(re, WebSocketMessageType.Text, true, CancellationToken.None);
             
        }

5.添加index.html

  前端发起websocket请求,依靠WebSocket对象,

  文档 http://www.ruanyifeng.com/blog/2017/05/websocket.html

    https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket

    https://www.runoob.com/html/html5-websocket.html

  这个对象比较简单,close()方法关闭连接,send()方法发消息,有几个相应事件,还有连接状态

 // 打开一个 web socket
     let ws = new WebSocket("ws://localhost:10800/ws");
// 打开
      ws.onopen = function (e) {
        // Web Socket 已连接上,使用 send() 方法发送数据
        printMsg('sebsocket连接成功!');
      };

      // 如果连接发生错误 不要使用try catch处理,使用这个事件
      ws.onerror = function (e) {
        printMsg('websocket初始化错误!');
      }

 

事件

open Socket.onopen 连接建立时触发
message Socket.onmessage 客户端接收服务端数据时触发
error Socket.onerror 通信发生错误时触发
close Socket.onclose 连接关闭时触发

 

 

 

 

 

方法

Socket.send()

使用连接发送数据

Socket.close()

关闭连接

 

 

 

 

6.测试

运行服务端程序,kestrel服务器开启监听

打开index.html文件,点击建立连接,发送一点消息,此时会发现不断收到消息

以前使用http要定时的发请求,这里没有发请求,服务端的报时消息发来了,说明websocket是长连接的

可以在另外打开一个浏览器,发起新的websocket连接,结果同样.

7.demo地址

https://github.com/mirrortom/Demo/tree/master/WebSocketTest

 

posted @ 2020-07-20 13:40  mirrorspace  阅读(873)  评论(0编辑  收藏  举报