基于H5的WebSocket简单实例
客户端代码:
1 <html> 2 <head> 3 <script> 4 var socket; 5 if ("WebSocket" in window) { 6 var ws = new WebSocket("ws://127.0.0.1:8181"); 7 socket = ws; 8 ws.onopen = function() { 9 console.log('连接成功'); 10 }; 11 ws.onmessage = function(evt) { 12 var received_msg = evt.data; 13 document.getElementById("showMes").value+=evt.data+"\n"; 14 }; 15 ws.onclose = function() { 16 alert("断开了连接"); 17 }; 18 } else { 19 alert("浏览器不支持WebSocket"); 20 } 21 function sendMes(){ 22 var message=document.getElementById("name").value+":"+document.getElementById("mes").value; 23 socket.send(message); 24 } 25 </script> 26 </head> 27 28 <body> 29 <textarea rows="3" cols="30" id="showMes" style="width:300px;height:500px;"></textarea> 30 <br/> 31 <label>名称</label> 32 <input type="text" id="name"/> 33 <br/> 34 <label>消息</label> 35 <input type="text" id="mes"/> 36 <button onclick="sendMes();">发送</button> 37 </body> 38 </html>
winform服务端代码:
注:需先引入Fleck包
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Windows.Forms; 5 using Fleck; 6 7 namespace socketService 8 { 9 public partial class Form1 : Form 10 { 11 public Form1() 12 { 13 InitializeComponent(); 14 CheckForIllegalCrossThreadCalls = false; 15 } 16 17 private void Form1_Load(object sender, EventArgs e) 18 { 19 //保存所有连接 20 var allSockets = new List<IWebSocketConnection>(); 21 //初始化服务端 22 var server = new WebSocketServer("ws://0.0.0.0:8181"); 23 //开始监听 24 server.Start(socket => 25 { 26 //有客户端连接触发 27 socket.OnOpen = () => 28 { 29 textBox3.Text += socket.ConnectionInfo.ClientIpAddress + " 连接 \r\n"; 30 allSockets.Add(socket); 31 }; 32 //有客户端断开触发 33 socket.OnClose = () => 34 { 35 textBox3.Text += socket.ConnectionInfo.ClientIpAddress + " 断开连接 \r\n"; 36 allSockets.Remove(socket); 37 }; 38 //接收客户端发送的消息 39 socket.OnMessage = message => 40 { 41 textBox3.Text += socket.ConnectionInfo.ClientIpAddress + " 发送了消息:" + message + "\r\n"; 42 //发送接收到的消息给所有客户端 43 allSockets.ToList().ForEach(s => s.Send(message)); 44 }; 45 }); 46 } 47 } 48 }