编程语言
首页 > 编程语言> > C# websocket类库Fleck学习

C# websocket类库Fleck学习

作者:互联网

前端:可以用这个篇介绍的代码,详解JS WebSocket断开原因和心跳机制

后端:winform程序编译成控制台程序

using Fleck;
 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            StartWebSocket();
        }

       static List<IWebSocketConnection> allSockets = new List<IWebSocketConnection>();
        private static void StartWebSocket()
        {
            FleckLog.Level = LogLevel.Debug;
            var server = new WebSocketServer("ws://0.0.0.0:7181");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                };
            });
        }

        /// <summary>
        /// 发消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            foreach (var socket in allSockets.ToList())
            {
                if (socket.IsAvailable == true)
                {
                    socket.Send(textBox2.Text);
                }
            }
            textBox2.Text = "";
        }

        /// <summary>
        /// 关闭所有连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //关闭与客户端的所有的连接
           foreach (var item in allSockets)
           {
               if (item != null)
               {
                   item.Close();
               }
           }
        }
    }

标签:类库,WebSocket,socket,SocketIO,C#,void,Fleck,Console,allSockets
来源: https://www.cnblogs.com/anjun-xy/p/16512275.html