当前位置:   article > 正文

WebSocket 简单示例_new websocketserver(ipaddress.any

new websocketserver(ipaddress.any

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;


                
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/964130
推荐阅读
相关标签
  

闽ICP备14008679号