一、服务器端开发,
public class SocketServer { static void Main() { try { FleckLog.Level = LogLevel.Debug; var allSockets = new List<IWebSocketConnection>();
//读取配置文件,值格式 ws://192.168.100.100:1234 string realNameUrl = Appsettings.app(new string[] { "WebApi", "RealNameUrl" }); var server = new WebSocketServer(realNameUrl); 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(); } } catch (Exception err) { FleckLog.Error(err.ToString()); } } }
二、客户端测试。最简单方法:
打开chrome——>F12——>输入如下代码:——>回车。如果是控制台,这时控制台中会显示出发送的内容:“websocekt测试”
ws = new WebSocket("ws://192.168.100.100:1234"); ws.onopen = function() { ws.send('websocekt测试'); }; ws.onmessage = function(e) { alert("收到服务端的消息:" + e.data); };
三、用静态html页面测试,代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>websocket client</title> <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/>"; // create a new websocket and connect window.ws = new wsImpl('ws://192.168.100.100:1234/'); // when data is comming from the server, this metod is called 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>
重点分享:
如果想用域名访问,必须要发布成IIS,如iis的域名为:test.xxxx-zhongguo.com:7890,服务器端启动,还是用IP 如:192.168.100.100:1234。
客户端访问就可以用 test.xxxx-zhongguo.com:1234。
代码参考:https://www.cnblogs.com/swjian/p/10553689.html