1.WebSocket 服务端

static void Main(string[] args)
{
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 1818);
FleckLog.Level = LogLevel.Debug;
var allSockets = new List<IWebSocketConnection>();
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();
}
}

 

2.WebSocket  客户端

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var start = function () {
var inc = document.getElementById('incomming');
var form = document.getElementById('sendForm');
var input = document.getElementById('sendText');

inc.innerHTML += "connecting to server ..<br/>";

// 创建新的websocket并连接
window.ws = new WebSocket("ws://127.0.0.1:1818");

// 当数据从服务器提交时,这个方法被调用
ws.onmessage = function (evt) {
inc.innerHTML += evt.data + '<br/>';
};

// 建立连接后,将调用此方法
ws.onopen = function () {
inc.innerHTML += '.. connection open<br/>';
};

// 当连接关闭时,将调用此方法
ws.onclose = function () {
inc.innerHTML += '.. connection closed<br/>';
}

form.addEventListener('submit', function (e) {
e.preventDefault();
var val = input.value;
ws.send(val);
input.value = "";
});
}
window.onload = start;
</script>
</head>
<body>
<form id="sendForm">
<input id="sendText" placeholder="Text to send" />
</form>
<pre id="incomming"></pre>
</body>
</html>