通过NuGget包安装Fleck包,引用using Fleck; winfrom代码如下
private void button1_Click(object sender, EventArgs e) { //启用按钮不可用 button1.Enabled = false; listBox1.Items.Add(DateTime.Now + "服务启用"); FleckLog.Level = LogLevel.Debug; var allSockets = new List<IWebSocketConnection>(); var server = new Fleck.WebSocketServer("ws://192.168.1.211:8212"); server.Start(socket => { socket.OnOpen = () => { listBox1.Items.Add(DateTime.Now + "客户端连接成功!"); allSockets.Add(socket); }; socket.OnClose = () => { listBox1.Items.Add(DateTime.Now + "客户端连接断开!"); allSockets.Remove(socket); }; socket.OnMessage = message => { Console.WriteLine(message); if (message!=null&& message!="") { Reception reception = new Reception(); try { reception = JsonConvert.DeserializeObject<Reception>(message); } catch (Exception) { allSockets.ToList().ForEach(s => s.Send(DateTime.Now + "客户端发送数据格式不正确")); } listBox1.Items.Add(DateTime.Now + "客户端发送的数据:" + message); ResponseMessage response = new ResponseMessage(); if (reception.description!="") { switch (reception.code) { //对接收消息的处理 } } } else { allSockets.ToList().ForEach(s => s.Send(DateTime.Now + "服务端接收数据为空")); } }; }); }