websoket服务端客户端demo
参考地址:https://www.cnblogs.com/zxtceq/p/6860022.html
参考地址:https://blog.csdn.net/ZslLoveMiwa/article/details/80247739
我们可以通过基础的Socket通信来实现和网页的相互通信。但由于只有在.net Framework在4.5以及4.5以上的版本对WebSocket通信的数据解析才有相关的类来支持。所以解析数据写起来十分的繁琐,所以我们使用第三方的库来完成低版本.net框架中的通信。如果仅仅是要从网页发送消息到服务器,那么我这边使用Flerk
Flerk github上有源码。(不太会用,我自己直接下的Flerk.dll)
一: 源码服务端代码(vs创建的控制台程序)
class Program { static void Main(string[] args) { FleckLog.Level = LogLevel.Debug; var allSockets = new List<IWebSocketConnection>(); var server = new WebSocketServer("ws://0.0.0.0:8181"); 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(); } } }
二:客户端页面
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> <script type="text/javascript"> var start = function () { var inc = document.getElementById('incomming'); var wsImpl = window.WebSocket || window.MozWebSocket; var form = document.getElementById('sendForm'); var input = document.getElementById('sendText'); inc.innerHTML += "connecting to server ..<br/>"; // 建立websoket连接 window.ws = new wsImpl('ws://localhost:8181/'); // 接收服务器端消息 ws.onmessage = function (evt) { inc.innerHTML += evt.data + '<br/>'; }; // when the connection is established, this method is called ws.onopen = function () { inc.innerHTML += '.. connection open<br/>'; }; // when the connection is closed, this method is called 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>
服务端客户端通信截图如下:

关闭其中一个soket通信结束


浙公网安备 33010602011771号