WebSocket instance a simple applet

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u011127019/article/details/91597197

A small side code program

<button bindtap='startConnect'>创建连接</button>
<button bindtap='sendOne'>发送内容</button>
<button bindtap='closeOne'>关闭连接</button>
//创建连接
startConnect: function () {
  //本地测试使用 ws协议 ,正式上线使用 wss 协议
  var url = 'ws://localhost:61870/socketone/one?user=lisi';
  wxst = wx.connectSocket({
    url: url,
    method: "GET"
  });
  wxst.onOpen(res => {
    console.info('连接打开成功');
  });
  wxst.onError(res => {
    console.info('连接识别');
    console.error(res);
  });
  wxst.onMessage(res => {
    var data = res.data;
    console.info(data);
  });
  wxst.onClose(() => {
    console.info('连接关闭');
  });
},
//发送内容
sendOne: function () {
  if (wxst.readyState == wxst.OPEN) {
    wxst.send({
      data: '小程序端测试',
      success: () => {
        console.info('客户端发送成功');
      }
    });
  } else {
    console.error('连接已经关闭');
  }
},
//关闭连接
closeOne: function () {
  wxst.close();
},

Second, the background Asp.Net MVC enable WebSocket

Note: Current examples consider only a single link is opened, in the case of multi-page open or in other words do not open the browser process.

/// <summary>
/// Socket后台代码示例
/// </summary>
public class SocketOneController : Controller
{
    static Dictionary<string, WebSocket> CONNECT_POOL = new Dictionary<string, WebSocket>();//用户连接池
                                                                                            //测试1,定义socke监听
    public void One(string user)
    {
        HttpContextBase context = ControllerContext.HttpContext;
        context.AcceptWebSocketRequest(async (ctx) =>
        {
            //开启socket监听
            WebSocket socket = ctx.WebSocket;

            while (true)
            {
                ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
                CancellationToken token;
                if (socket.State == WebSocketState.Open)
                {
                    //后台上线处理
                    if (CONNECT_POOL.Keys.Contains(user) == false)
                        CONNECT_POOL.Add(user, socket);

                    WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, token);
                    string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);

                    userMessage = "You sent: " + userMessage + " at " +
                    DateTime.Now.ToLongTimeString();

                    //响应处理
                    buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
                    await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                else
                {
                    //离线处理
                    CONNECT_POOL.Remove(user);
                    break;
                }
            }
        });
    }
    //后台执行发送操作
    public string Handle(string user)
    {
        if (CONNECT_POOL.Keys.Contains(user) == false)
            return "当前连接已经断开";

        WebSocket socket = CONNECT_POOL[user];

        byte[] bytes = Encoding.UTF8.GetBytes($"后台发送通知 at {DateTime.Now.ToString()}");
        ArraySegment<byte> buffer = new ArraySegment<byte>(bytes);
        socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);

        return "操作成功";
    }
}

 

More:

Four examples HTML5 WebSocket + Asp.Net - user ID, push back

Asp.Net Core SignalR acquisition hub example, sending a message from the external hub

 Asp.Net Core 2.0 technology using SignalR - Getting Started

Guess you like

Origin blog.csdn.net/u011127019/article/details/91597197