websocket 学习
一、服务器端开发,
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。
步骤:
1、连接socket。并带参数。
2、socket接受到连接信息请求,可以记录下对应IP和port,根据定义进行解析参数。 还可以把所有的连接信息(如机器识别码),进行缓存
3、连接成功后,可以通过IP和port向指定客户端发送信息。
4、其他接口向socket直接发送信息(如下)。
5、接受到信息,可以对缓存连接信息进行过滤,向对应(根据机器识别码)的客户端推送及时信息。
其他使用:
private readonly ClientWebSocket webSocket = new ClientWebSocket(); private readonly CancellationToken _cancellation = new CancellationToken(); /// <summary> /// 发送连接 /// 支持中文 /// </summary> /// <param name="serverIP">目标IP</param> /// <param name="message">发送信息</param> /// <param name="port">目标端口</param> public async Task tcpSendText(string serverIP, int port, object message) { await webSocket.ConnectAsync(new Uri("ws://"+ serverIP + ":"+ port ), _cancellation); var sendBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));//发送的数据 var bsend = new ArraySegment<byte>(sendBytes); await webSocket.SendAsync(bsend, WebSocketMessageType.Text, true, _cancellation); await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "1", _cancellation); webSocket.Dispose(); }
代码参考:https://www.cnblogs.com/swjian/p/10553689.html