C# websocket 使用备忘

1、websocket服务端,采用开源组件[Fleck],如果需要用TSL则需要IIS版本的域名的SSL证书和证书密码。

public class WbService
    {
        static List<IWebSocketConnection> allSockets;
        static WebSocketServer server;
        public static void Start()
        {
            FleckLog.Level = LogLevel.Debug;
            allSockets = new List<IWebSocketConnection>();
            server = new WebSocketServer("wss://0.0.0.0:8181/");
            string certificatePath = "c:\cert\xxx.pfx";
            string password = "xxxxx";
            server.Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificatePath, password);
            //默认是tsl1.0版本 但是最新版的谷歌浏览器等已经不支持,所以要启用TSL1.2
            server.EnabledSslProtocols = SslProtocols.Tls12;
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    ConsoleWrite(socket.ConnectionInfo.ClientIpAddress + ":" + message);
                    //socket.Send("Reple: " + message);
                    allSockets.ToList().ForEach(s => s.Send(message));
                };
                socket.OnPing = pdata =>
                {
                    socket.SendPing(pdata);
                };

               
            });
            ConsoleWrite("启动成功.");
        }

        // 打印日志 
        public static void ConsoleWrite(string msg)
        {
            StartServer.consoleBox.AppendText("WebSocket服务:" + msg + "  " + DateTime.Now.ToString() + "
");
            StartServer.consoleBox.AppendText("
");
        }

        
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="message"></param>
        public static void Send(string message)
        {
            foreach (var socket in allSockets.ToList())
            {
                socket.Send(message);
            }
            ConsoleWrite(message);
        }
    }
View Code

2、客户端 除了JS外·有时候在C#中也需要用到websocket,那么就需要用到WebSocketSharp开源组件
使用方法如下:

using (var ws = new WebSocket("wss://127.0.0.1:8181/"))
                {
                    //必须和服务器TSL版本一致
                    ws.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls12;
                    ws.OnMessage += (sender2, e2) =>
                        Console.WriteLine("Laputa says: " + e2.Data);

                    ws.Connect();
                    string json = JsonConvert.SerializeObject(obj2);
                    ws.Send(json);
                    ws.Close();
                    //Console.ReadKey(true);
                }
View Code
原文地址:https://www.cnblogs.com/liaoyi/p/13816262.html