โค้ดตัวอย่างของ WebSocket ที่ใช้ HTML5
รหัสลูกค้า:
<html><head><script>var socket;if (WebSocket ในหน้าต่าง) {var ws = new WebSocket(ws://127.0.0.1:8181);socket = ws;ws.onopen = function() {console. log ('การเชื่อมต่อสำเร็จ');}; ws.onmessage = function (evt) {varที่ได้รับ_msg = evt.data; document.getElementById(showMes).value+=evt.data+/n;};ws.onclose = function() {alert(disconnected);};} else {alert(browser does not support WebSocket);}function เข้าสู่ระบบ (){ var message=document.getElementById(name).value+:+document.getElementById(mes).value;socket.send(message);}</script></head><body><textarea rows=3 cols=30 id= showMes style=width:300px;height:500px;></textarea><br/><label>ชื่อ</label><input type=text id=name/><br/><label>ข้อความ</label><input type=text id=mes/><button onclick=login();>ส่ง</button></body></ html>
รหัสเซิร์ฟเวอร์ winform:
หมายเหตุ: จำเป็นต้องแนะนำแพ็คเกจ Fleck ก่อน
การใช้ระบบ; การใช้ System.Collections.Generic; การใช้ System.Linq; การใช้ System.Windows.Forms; การใช้ Fleck; เนมสเปซ socketService {คลาสสาธารณะบางส่วน Form1 : แบบฟอร์ม {public Form1(){InitializeComponent();CheckForIllegalCrossThreadCalls = false;}private เป็นโมฆะ Form1_Load (ผู้ส่งวัตถุ EventArgs e){// บันทึกการเชื่อมต่อทั้งหมด var allSockets = ใหม่ รายการ<IWebSocketConnection>();//เตรียมใช้งานเซิร์ฟเวอร์ var server = new WebSocketServer(ws://0.0.0.0:8181);//Start Listening server.Start(socket =>{//A การเชื่อมต่อไคลเอนต์ทริกเกอร์ซ็อกเก็ต OnOpen = () =>{textBox3.Text += socket.ConnectionInfo.ClientIpAddress + Connection/r/n;allSockets.Add(socket);};//การตัดการเชื่อมต่อไคลเอ็นต์ทริกเกอร์ socket.OnClose = () =>{textBox3.Text += socket.ConnectionInfo.ClientIpAddress + Disconnect/r/n ;allSockets.Remove( socket);};//รับข้อความที่ส่งโดยซ็อกเก็ตไคลเอ็นต์OnMessage = message =>{textBox3.Text += socket.ConnectionInfo.ClientIpAddress + ส่งข้อความ: + ข้อความ + /r/n;//ส่งข้อความที่ได้รับไปยังลูกค้าทั้งหมด allSockets.ToList().ForEach(s => s.Send(message));} }) ;}}}สรุป
ข้างต้นคือโค้ดตัวอย่างของ WebSocket ที่ใช้ HTML5 ที่บรรณาธิการแนะนำ ฉันหวังว่ามันจะเป็นประโยชน์กับคุณ หากคุณมีคำถามใดๆ โปรดฝากข้อความถึงฉัน แล้วบรรณาธิการจะตอบกลับคุณทันเวลา ฉันอยากจะขอบคุณทุกคนที่ให้การสนับสนุนเว็บไซต์ศิลปะการต่อสู้ VeVb!