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