WebSocket 服务端
static void Main(string[] args) { IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 1818); FleckLog.Level = LogLevel.Debug; var allSockets = new List(); var server = new WebSocketServer(“ws://”+ localEP + “”); server.Start(socket => { socket.OnOpen = () => { Console.WriteLine(“Open!”); allSockets.Add(socket); }; socket.OnClose = () => { Console.WriteLine(“Close!”); allSockets.Remove(socket); }; socket.OnMessage = message => { Console.WriteLine(message); allSockets.ToList().ForEach(s => s.Send("Echo: " + message)); }; });
var input = Console.ReadLine(); while (input != “exit”) { foreach (var socket in allSockets.ToList()) { socket.Send(input); } input = Console.ReadLine(); } }
WebSocket 客户端
inc.innerHTML += “connecting to server … ”;
// 创建新的websocket并连接 window.ws = new WebSocket(“ws://127.0.0.1:1818”);
// 当数据从服务器提交时,这个方法被调用 ws.onmessage = function (evt) { inc.innerHTML += evt.data + ‘ ’; };
// 建立连接后,将调用此方法 ws.onopen = function () { inc.innerHTML += ‘… connection open ’; };
// 当连接关闭时,将调用此方法 ws.onclose = function () { inc.innerHTML += ‘… connection closed ’; }
form.addEventListener(‘submit’, function (e) { e.preventDefault(); var val = input.value; ws.send(val); input.value = “”; }); } window.onload = start;
|