处事端使用Nuget引用SuperSocket.WebSocket和SuperSocket.Engine
处事器端代码【控制台】
using SuperSocket.WebSocket; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Server { class Program { static void Main(string[] args) { WebSocketServer server = new WebSocketServer(); server.NewSessionConnected += server_NewSessionConnected; server.NewMessageReceived += server_NewMessageReceived; server.SessionClosed += server_SessionClosed; try { server.Setup("127.0.0.1", 40001);//设置端口 server.Start();//开启监听 PushMsg(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); } static void PushMsg() { Thread.Sleep(1000); try { sessionList.ForEach(o => { o.Send("测试动静推送"); }); } catch (Exception ex) { } PushMsg(); } public static List<WebSocketSession> sessionList = new List<WebSocketSession>(); static void server_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value) { sessionList.Remove(session); Console.WriteLine(session.Origin); } static void server_NewMessageReceived(WebSocketSession session, string value) { Console.WriteLine(value); session.Send(value); } static void server_NewSessionConnected(WebSocketSession session) { sessionList.Add(session); Console.WriteLine(session.Origin); } } }
View Code客户端代码【网站】
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <textarea id="textarea" style="height: 500px; width: 300px;"></textarea> <input type="button" id="send" onclick="send()" value="发送"> <input type="text" id="message"> <script type="text/javascript"> //查抄浏览器是否撑持WebSocket if (!window.WebSocket) { console.log(‘您的浏览器不撑持WebSocket,请选择其他的浏览器再测验考试连接处事器‘); } var el = document.getElementById("textarea"); var wsClient = new WebSocket(‘ws://localhost:40001‘); wsClient.open = function (e) { el.value += "连接告成!\r\n"; } wsClient.onclose = function (e) { el.value += "连接断开!\r\n"; } wsClient.onmessage = function (e) { el.value += "接收动静:" + e.data + "\r\n"; } wsClient.onerror = function (e) { el.value += "连接掉败!原因【" + e.data + "】\r\n"; } function send() { var oText = document.getElementById("message"); wsClient.send(oText.value); } </script> </body> </html>
View Code措施目录布局
效果
,