Example code of WebSocket based on HTML5
Client code:
<html><head><script>var socket;if (WebSocket in window) {var ws = new WebSocket(ws://127.0.0.1:8181);socket = ws;ws.onopen = function() {console. log('Connection successful');};ws.onmessage = function(evt) {var received_msg = evt.data; document.getElementById(showMes).value+=evt.data+/n;};ws.onclose = function() {alert(disconnected);};} else {alert(browser does not support WebSocket);}function login (){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>Name</label><input type=text id=name/><br/><label>Message</label><input type=text id=mes/><button onclick=login();>Send</button></body></ html>
winform server code:
Note: The Fleck package needs to be introduced first
using System;using System.Collections.Generic;using System.Linq;using System.Windows.Forms;using Fleck;namespace socketService{public partial class Form1 : Form{public Form1(){InitializeComponent();CheckForIllegalCrossThreadCalls = false;}private void Form1_Load(object sender, EventArgs e){//Save all connections var allSockets = new List<IWebSocketConnection>();//Initialize the server var server = new WebSocketServer(ws://0.0.0.0:8181);//Start listening server.Start(socket =>{//A client connection triggers the socket. OnOpen = () =>{textBox3.Text += socket.ConnectionInfo.ClientIpAddress + Connection/r/n;allSockets.Add(socket);};//Client disconnection triggers socket.OnClose = () =>{textBox3.Text += socket.ConnectionInfo.ClientIpAddress + Disconnect/r/n ;allSockets.Remove(socket);};//Receive messages sent by the client socket.OnMessage = message =>{textBox3.Text += socket.ConnectionInfo.ClientIpAddress + sent a message: + message + /r/n;//Send the received message to all clients allSockets.ToList().ForEach(s => s.Send(message));}; });}}}Summarize
The above is the example code of WebSocket based on HTML5 introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for your support of the VeVb martial arts website!