服务端使用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); } } }
客户端代码【网站】
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <textarea id="textarea" style="height: 500px; 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 += "连接成功! "; } wsClient.onclose = function (e) { el.value += "连接断开! "; } wsClient.onmessage = function (e) { el.value += "接收消息:" + e.data + " "; } wsClient.onerror = function (e) { el.value += "连接失败!原因【" + e.data + "】 "; } function send() { var oText = document.getElementById("message"); wsClient.send(oText.value); } </script> </body> </html>
效果 :
程序目录结构