C# WebSocket 服务器与客户端通讯

第一步:在vs的NuGet里导入Fleck包,选择自己想要安装的项目安装 https://pan.baidu.com/s/1o9jU22e
与客户端类库websocket-sharp.dll 

第二步、WebSocket 服务器代码:

public List<IWebSocketConnection> WsClient { get; private set; }
private readonly WebSocketServer server;
public WsServer(int port = 8081)
		{
			WsServer.Port = port;
			Dictionary<string, Func<string, WsResutl>> dictionary = new Dictionary<string, Func<string, WsResutl>>();
			dictionary.Add("/hi", (string msg) => new WsResutl("Hello world! Echo:" + msg));
			this.RouteFunc = dictionary;
			this.server = new WebSocketServer(string.Format("ws://0.0.0.0:{0}", WsServer.Port), true);
			this.WsClient = new List<IWebSocketConnection>();
		}
public void Start()
		{
			this.server.RestartAfterListenError = true;
			this.server.Start(delegate(IWebSocketConnection socket)
			{
				socket.OnOpen = delegate
				{
					string clientIpAddress = socket.ConnectionInfo.ClientIpAddress;
					string path = socket.ConnectionInfo.Path;
					FleckLog.Info("Open:" + clientIpAddress + " path:" + path, null);
					if (this.RouteFunc.ContainsKey(path))
					{
						this.WsClient.Add(socket);
						return;
					}
					socket.Close();
				};
				socket.OnMessage = delegate(string msg)
				{
					string path = socket.ConnectionInfo.Path;
					FleckLog.Debug("Message:" + path, null);
					if (this.RouteFunc.ContainsKey(path))
					{
						Func<string, WsResutl> func = this.RouteFunc[path];
						WsResutl wsResutl = (func != null) ? func(msg) : null;
						if (wsResutl != null)
						{
							byte[] byteArray = wsResutl.ByteArray;
							int? num = (byteArray != null) ? new int?(byteArray.Length) : null;
							int num2 = 0;
							if (num.GetValueOrDefault() > num2 & num != null)
							{
								socket.Send(wsResutl.ByteArray);
                                // WsClient.ToList().ForEach(s => s.Send("test"));
							}
						}
					}
				};
				socket.OnClose = delegate
				{
					FleckLog.Debug("Close:" + socket.ConnectionInfo.ClientIpAddress, null);
					this.WsClient.Remove(socket);
				};
			});
		}
public void Stop()
		{
			try
			{
				this.server.Dispose();
			}
			catch (Exception)
			{
			}
		}
 internal class WsResutl : HttpResutl
	{
		public WsResutl(string content) : base(200)
		{
			base.ByteArray = Encoding.UTF8.GetBytes(content);
		}
		public WsResutl(byte[] Bytes) : base(200)
		{
			base.ByteArray = Bytes;
		}
		public WsResutl() : base(200)
		{
			base.ByteArray = new byte[0];
		}
	}

第三步、WebSocket 客户端代码:

WebSocket ws;
 bool isConnected;

        public void Connect()
        {
            try
            {
                if (isConnected == false)
                {
                    ws = new WebSocket("ws://localhost:9999");
                    ws.OnOpen += ws_OnOpen;
                    ws.OnMessage += ws_OnMessage;
                    ws.OnClose += ws_OnClose;
                    ws.Connect();
                }
            }
            catch (Exception ex)
            {
            }
        }

        void ws_OnOpen(object sender, EventArgs e)
        {
            SetTextBoxText(textBox1, "已连接服务器" + "\r\n");
            isConnected = true;

        }
        void ws_OnClose(object sender, CloseEventArgs e)
        {
            SetTextBoxText(textBox1, "服务器已断开" + "\r\n");
            isConnected = false;
        }

        void ws_OnMessage(object sender, MessageEventArgs e)
        {
            try
            {
                string message = e.Data;

                //显示接收的服务器信息
                SetTextBoxText(textBox1, message);

                //给服务器发送信息
                ws.Send("Hello World!");
            }

            catch (Exception ex)
            {
            }
        }
        public delegate void DelSetTextBoxText(TextBox txtBox, string str);
        public void SetTextBoxText(TextBox txtBox, string str)
        {
            if (txtBox.InvokeRequired)
            {
                DelSetTextBoxText del = new DelSetTextBoxText(SetTextBoxText);
                this.Invoke(del, new object[] { txtBox, str });
            }
            else
            {
                txtBox.Text += str + "\r\n";
            }
        }

 

posted @   多见多闻  阅读(1854)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示