-
XIaoFeng网络库SocketServer,WebSocketServer,SocketClient,WebSocketClient作者 : Jacky 发布于 2023-08-04 10:41:52 浏览 957 次新的网络库重构了SocketServer,WebSocketServer,SocketClient,WebSocketClient
1.服务端 SocketServer,WebSocketServer
SocketServer
当前库同时支持Socket请求,WebSocket请求连接
WebSocketServer仅支持WebSocket请求连接//仅支持WebSocket连接 var c = new WebSocketServer(8010); //支持Socket 和WebSocket连接 //var c = new SocketServer(8010); //支持SSL c.SslProtocols = System.Security.Authentication.SslProtocols.Tls12; c.Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate(@"E:\\a.eelf.cn.pfx", "7092734"); c.OnStart += (o, e) => { Console.WriteLine("项目启动."); }; c.OnAuthentication += (c, m, e) => { //认证事件 }; c.Authentication = c => { //认证方法 return true; }; c.OnStop += (c, e) => { Console.WriteLine("项目停止."); }; c.OnMessage += (c, m, e) => { Console.WriteLine($"接收到消息[{c.EndPoint}](text):{m}"); c.Send(m); }; c.OnMessageByte += (c, m, e) => { Console.WriteLine($"接收到消息[{c.EndPoint}](bytes):{m.GetString()}"); c.Send(m); }; c.OnError += (c, e) => { Console.WriteLine("出错:" + e.Message); }; c.OnNewConnection += (c, e) => { Console.WriteLine($"新连接[{c.EndPoint}]"); }; c.OnDisconnected += (c, e) => { Console.WriteLine($"断开连接[{c.EndPoint}]"); }; c.OnClientError += (c, e) => { Console.WriteLine($"客户端出错[{c.EndPoint}]:{e.Message}"); }; c.Start();
其它方法
//停止监听服务 c.Stop(); //添加请求黑名单IP c.AddBlack("11.12.12.13", "1.2.3.58"); //群发消息 c.Send("群发消息"); //发送消息给所有订阅当前频道的客户 c.Send("消息".GetBytes(), "频道1", "频道2"); //客户端列表 var clients = c.Clients;
WebSocketServer 还有特定方法就是可以设置自动pong,防止2分钟客户端无信息浏览器自动断开的情况;
//启动pong c.IsPong = true; //每隔120秒发送一次 c.PongTime = 120;
2.Client客户端 SocketClient,WebSocketClient
SocketClient 连接 SocketServer的客户端
WebSocketClient 连接 SocketServer,WebSocketServer的客户端var c = new SocketClient("127.0.0.1", 8010); //var c = new WebSocketClient("ws://127.0.0.1:8010/ws"); //var c = new WebSocketClient("wss://localhost:8010/ws"); c.OnStart += (o,e)=> { Console.WriteLine("项目启动."); }; c.OnStop += (c, e) => { Console.WriteLine("项目停止."); }; c.OnMessage += (c, m, e) => { Console.WriteLine("接收到消息(text):" + m); }; c.OnMessageByte += (c, m, e) => { Console.WriteLine("接收到消息(bytes):" + m.GetString()); }; c.OnClientError += (c, e) => { Console.WriteLine("出错:" + e.Message); }; //启动 c.Start(); //发送消息 c.SendAsync("消息"); //发送Ping信息 c.SendPingAsync(); //停止连接服务 c.Stop();
所有评论(0)