客戶端代碼: <html><head> <script> var socket; if ("WebSocket" in window) { var ws = new WebSocket("ws://127.0.0.1:8181"); socket = ws; ws.onopen = function ...
客戶端代碼:
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 }