【WebSocket】 有感

【WebSocket】

搞了这么长时间的websocket 终于有一些自己的感悟了,多的不说直接上代码。

服务端 =>

using DataHelper.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.WebSockets;

namespace DayDayUpCore.WebSocketHandler
{
    /// <summary>
    /// WebSocketHandler 的摘要说明
    /// WS客户端
    /// </summary>
    public class WebSocketHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get => false;
        }


        public void ProcessRequest(HttpContext context)
        {
            if (context.IsWebSocketRequest)
                context.AcceptWebSocketRequest(async WsContext =>
                {
                    WebSocket socket = WsContext.WebSocket;
                    var userName = WsContext.QueryString["user"].ToString();
                    try
                    {
                        ChatManager.AddUser(userName, socket);
                        var targetUser = "";
                        while (socket.State == WebSocketState.Open)
                        {
                            try
                            {
                                var buffer = new ArraySegment<byte>(new byte[12000]);
                                var receiveMesInfo = await socket.ReceiveAsync(buffer, CancellationToken.None);
                                if (receiveMesInfo.MessageType == WebSocketMessageType.Close)
                                    ChatManager.RemoveUser(userName);
                                else
                                {
                                    var userMesInfo = Encoding.UTF8.GetString(buffer.Array, 0, receiveMesInfo.Count);
                                    var MesInfo = JsonConvert.DeserializeObject<MessageInfo>(userMesInfo);
                                    targetUser = MesInfo.Target;
                                    if (string.IsNullOrWhiteSpace(targetUser) || ChatManager.UserPool.ContainsKey(targetUser))
                                       await ChatManager.SendMessage(userMesInfo, targetUser);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception(ex.Message);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                });
        }

        /// <summary>
        /// 管理用户类
        /// </summary>
        private static class ChatManager
        {
            /// <summary>
            /// 用户连接池
            /// </summary>
            public static Dictionary<string, WebSocket> UserPool = new Dictionary<string, WebSocket>();

            /// <summary>
            /// 添加用户
            /// </summary>
            /// <param name="userName">用户名</param>
            /// <param name="socket">WebSocket</param>
            public static void AddUser(string userName, WebSocket socket)
            {
                UserPool[userName] = socket;
            }

            /// <summary>
            /// 删除用户
            /// </summary>
            /// <param name="userName">用户名</param>
            public static void RemoveUser(string userName)
            {
                if (UserPool.ContainsKey(userName))
                    UserPool.Remove(userName);
            }

            /// <summary>
            /// 目的用户名,如果为空则广播消息
            /// </summary>
            /// <param name="MesInfo">消息</param>
            /// <param name="TargetUser">目的用户名,如果为空或用户不存在则广播消息</param>
            /// <returns></returns>
            public static async Task SendMessage(string MesInfo, string TargetUser = "")
            {
                try
                {
                    var SegmentJson = new ArraySegment<byte>(Encoding.UTF8.GetBytes(MesInfo));
                    if (string.IsNullOrWhiteSpace(TargetUser) || !UserPool.ContainsKey(TargetUser))
                    {
                        foreach (var item in UserPool.Select(s => s.Value))
                        {
                            await item.SendAsync(SegmentJson, WebSocketMessageType.Text, true, CancellationToken.None);
                        }
                    }
                    else
                        await UserPool[TargetUser].SendAsync(SegmentJson, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                catch (Exception ex)
                {

                    throw new Exception(ex.Message);
                }
            }
        }

        /// <summary>
        /// 消息模板
        /// </summary>
        private class MessageInfo
        {
            /// <summary>
            /// 目的用户
            /// </summary>
            public string Target { get; set; }
            /// <summary>
            /// 消息标题
            /// </summary>
            public string MesTitle { get; set; }
            /// <summary>
            /// 消息内容
            /// </summary>
            public string MesData { get; set; }
        }
    }
}

前端 =>

/**

  • 初始化WebSocket

  • /
    class WebSocketInit {
    /
    *

    • 构造函数

    • @param {any} url

    • @param {any} mesEvent 监听消息
      /
      constructor(url, mesEvent) {
      this.Url = url;
      this.OnMessage = mesEvent;
      this.Ws;
      var support = “MozWebSocket” in window ? “MozWebSocket” : (‘WebSocket’ in window ? ‘WebSocket’ : null);
      if (support == null) {
      alert(“浏览器不支持WebSocket!”);
      return false;
      }
      this.Connect(this.Url);
      }
      /
      *

    • 连接websocket

    • @param {any} url
      */
      Connect(url) {
      try {
      this.Ws = new WebSocket(url);
      if (this.Ws.readyState === WebSocket.CONNECTING)
      console.log(“正在连接WebSocket服务器…”);

       this.Ws.onopen = this.OnOpen;
       this.Ws.onmessage = this.OnMessage;
       this.Ws.onclose = this.OnClose;
       this.Ws.onerror = this.OnError;
      

      }
      catch (e) {
      console.log(“ConnectError:” + e);
      }
      }

    DisConnect() {
    if (this.Ws && this.Ws.readyState === WebSocket.OPEN) {
    this.Ws.close(); //关闭TCP连接
    console.log(‘连接已关闭’);
    }
    }

    OnOpen() {
    if (this.Ws && this.Ws.readyState === WebSocket.OPEN)
    console.log(‘WebSocket已连接’);
    }

    OnClose(e) {
    if (e.code == 1006) //当遇到不明状态websocket关闭,启用心跳起搏
    this.Connect(this.Url);
    }

    OnError(e) {
    console.log(e)
    }
    /**

    • 发送消息
    • @param {any} MesInfo
      */
      SendMessage(MesInfo) {
      if (this.Ws != null && this.Ws.readyState === WebSocket.OPEN) {
      if (!MesInfo)
      return;
      this.Ws.send(MesInfo);
      }
      else
      console.log(“发送失败!”);
      }

    GetWebSocketState() {
    return this.Ws.readyState;
    }
    }

/**

  • 消息模板
  • /
    class MessageInfo {
    /
    *
    • 构造函数
    • @param {any} target 目的用户
    • @param {any} mesTitle 消息标题
    • @param {any} mesData 消息数据
      */
      constructor(target, mesTitle, mesData) {
      this.Target = target;
      this.MesTitle = mesTitle;
      this.MesData = mesData;
      }
      }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值