using SuperSocket.ClientEngine; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using WebSocket4Net; namespace XHZB.Desktop.WebSocket { public class SocketClient { // 打开的窗口列表 private static readonly Dictionary WinDic = new Dictionary(); private static SocketClient instance; public static SocketClient getInstance() { if (instance == null) { instance = new SocketClient(); } return instance; } static void Starts() { //新建客户端类 //服务端IP地址 ws://192.168.1.13 如果服务端开启了ssl或者tsl 这里前缀应该改成 wss:/ //服务端监听端口 1234 //自定义的地址参数 可以根据地址参数来区分客户端 /lcj控制台 //WSocketClient client = new WSocketClient("wss://a.lcj888.ml:54645/lcj控制台"); WSocketClient client = new WSocketClient("ws://schoolwstest.xhkjedu.com/ws"); //注册消息接收事件,接收服务端发送的数据 client.MessageReceived += (data) => { Console.WriteLine(data); }; //开始链接 client.Start(); Console.WriteLine("输入“c”,退出"); var input = ""; do { input = Console.ReadLine(); //客户端发送消息到服务端 client.SendMessage(input); } while (input != "c"); client.Dispose(); } /// /// 添加要推送消息的窗口 /// /// public void addWin(object win) { if (WinDic.ContainsKey(win.GetType())) { WinDic[win.GetType()] = win; } else { WinDic.Add(win.GetType(), win); } } /// /// 发送给需要接收的窗口 /// private static void sendUserChangeToWin() { foreach (KeyValuePair kvp in WinDic) { if (kvp.Value is SocketCallback callback) { callback.userListChange(); } } } /// /// 移除窗口 /// /// public void removedWin(object win) { if (WinDic.ContainsKey(win.GetType())) { WinDic.Remove(win.GetType()); } } } }