C# 实现WebSocket通信


使用背景

首先说一下用websocket的背景,因为公司新开发了小程序的业务,需要用的通讯即服务器推送消息给小程序。

一开始项目中使用的是 SignalR 因为小程序不支持所以更改使用websocket

具体实现

 首先要在NuGet导入“Fleck”包,需 .NET Framework 4.5及以上。

 

 

然后定义一个PushHelper的一个推送帮助类:

ws://0.0.0.0:3301 这个是本机地址,然后端口名是3301 这个不能占用。

然后websocket这个地址是可以增加自定义参数的,如:?id=“1”&name=“张三”

本项目使用的是groupname和groupvalue这两个参数;

具体实现可以看代码的封装。

 

using Coldairarrow.Util.Helper;
using Fleck;
using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Coldairarrow.Util
{
    public class PushHelper
    {
        /// <summary>
        /// 所有的连接
        /// </summary>
        public static List<WebsocketDB> allSockets = new List<WebsocketDB>() { };
        //public static List<IWebSocketConnection> allSockets = new List<IWebSocketConnection>();





        /// <summary>
        /// webscoket服务端实例
        /// </summary>
        public static WebSocketServer server = new WebSocketServer("ws://0.0.0.0:3301");













        //通知前端刷新页面
        public static void ReloadPage(string AuctionId)
        {
            Send("ReloadPage", AuctionId, "reload-" + AuctionId);
        }


     

        /// <summary>
        /// 推送发言
        /// </summary>
        /// <param name="MarkId"></param>
        /// <param name="ajaxResult"></param>
        public static void AuctioneerSpeakAuction(string MarkId, ChartDTO ajaxResult)
        {
            Send("Speak", MarkId, ajaxResult.ToJson());
        }





     





        /// <summary>
        /// 初始化websocket服务
        /// </summary>
        public static void Dosocket()
        {
            try
            {
                server.Start(socket =>
                {
                    var strSocket = socket.ConnectionInfo.Path.Substring(1);
                    var dicQ = StringHelper.GetQueryString(strSocket);
                    var groupN = dicQ["GroupName"];
                    var groupV = dicQ["GroupValue"];
                    WebsocketDB websocket = new WebsocketDB() { GroupName = groupN, GroupValue = groupV, Socket = socket };
                    socket.OnOpen = () =>
                    {

                        allSockets.Add(websocket);
                        //这是把每一个socket添加到allScokets中(表示当有一个页面连接上这个socket的时候,就会多一个socket)
                    };
                    //关闭链接
                    socket.OnClose = () =>
                    {

                        allSockets.Remove(websocket);
                        //用户断开socket连接时,就把这个用户的socket移除
                    };
                });
            }
            catch (Exception ex)
            {

                throw;
            }

        }

        /// <summary>
        /// 封装websocket推送模板
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="groupValue"></param>
        /// <param name="res"></param>
        public static void Send(string groupName, string groupValue, byte[] res)
        {
            var sockets = allSockets.Where(x => x.GroupName == groupName && x.GroupValue == groupValue).ToList();
            foreach (var item in sockets)
            {
                item.Socket.Send(res);

            }
        }

        /// <summary>
        /// 封装websocket发送接口
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="groupValue"></param>
        /// <param name="res"></param>
        public static void Send(string groupName, string groupValue, string res)
        {
            var sockets = allSockets.Where(x => x.GroupName == groupName && x.GroupValue == groupValue).ToList();
            foreach (var item in sockets)
            {
                item.Socket.Send(res);

            }
        }



    }


    public class WebsocketDB
    {
        public string GroupName { get; set; }

        public string GroupValue { get; set; }

        /// <summary>
        ///  连接对象
        /// </summary>
        public IWebSocketConnection Socket { get; set; }
    }


 
}

定义之后就可以在项目启动时调用一下,这里以mvc为例:

在RouteConfig.cs下面进行调用。

 

 

 

 

 前端代码:

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>

<body>
    <textarea id="textarea" style="height: 500px; width: 300px;"></textarea>
    <input type="button" id="send" onclick="send()" value="发送">

    <input type="text" id="message">
    <script type="text/javascript">
        //检查浏览器是否支持WebSocket
        if (!window.WebSocket) {
            console.log('您的浏览器不支持WebSocket,请选择其他的浏览器再尝试连接服务器');
        }
        var el = document.getElementById("textarea");

        var wsClientSp2 = new WebSocket('ws://localhost:3301?GroupName=Speak&GroupValue=1410879750406148096');
        /*        var wsClient = new WebSocket('ws://localhost:7181/add');//方法2  */

        wsClientSp2.open = function (e) {
            el.value += "连接成功!\r\n";
        }
        wsClientSp2.onclose = function (e) {
            el.value += "连接断开!\r\n";
        }
        wsClientSp2.onmessage = function (e) {
/*            console.log(wsClient);*/
            el.value += "接收消息:" + e.data + "\r\n";
        }
        wsClientSp2.onerror = function (e) {
            el.value += "连接失败!原因【" + e.data + "】\r\n";
        }


        function send() {
            //var oText = document.getElementById("message");
            //wsClient.send(oText.value);
        }
    </script>
</body>

</html>

 

最后上一个成品图

 

 

我是一个不断学习和成长的黄金程序员,欢迎评论与我交流技术问题。

欢迎评论(期待ing)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM