public static async Task SendStringAsync(BitNoticeMessage message, bool isLocal = false) { foreach (var user in sockets) { if (user.Key != message.Receiver) { continue; } foreach (var socket in user.Value) { //LogHelper.SaveLog("WebSockets", string.Format("发送消息:{0}:{1}:{2}:{3}", socket.IsRemote, socket.RemoteIp, socket.RemoteTime, JsonConvert.SerializeObject(message))); if (socket.IsRemote && !isLocal) {//远程通道 try { WebClient wc = new WebClient(); byte[] sendByte = Encoding.Default.GetBytes(JsonConvert.SerializeObject(message)); var url = string.Format("http://{0}:1899/BitService/SendWebSocketString", socket.RemoteIp); //LogHelper.SaveLog("WebSockets", string.Format("发送远程消息:{0}", url)); var result = wc.UploadData(url, sendByte); var strResult = Encoding.Default.GetString(result); } catch (Exception ex) { LogHelper.SaveLog(ex); } } else if (socket.WebSocket.State == WebSocketState.Open) {//本地通道 await SendStringAsync(socket.WebSocket, JsonConvert.SerializeObject(message), socket.HttpContext.RequestAborted); } } } }
static async Task Acceptor(HttpContext context, Func <Task> n) { if (!context.WebSockets.IsWebSocketRequest || !SSOClient.IsLogin) { return; } CancellationToken ct = context.RequestAborted; var currentSocket = await context.WebSockets.AcceptWebSocketAsync(); string sid = SSOClient.UserId.ToString(); if (!sockets.ContainsKey(sid)) { sockets.TryAdd(sid, new List <UserSocket>()); } sockets[sid].Add(new UserSocket() { HttpContext = context, WebSocket = currentSocket, IsRemote = false }); while (true) { if (ct.IsCancellationRequested) { break; } string request = await ReceiveStringAsync(currentSocket, ct); if (string.IsNullOrEmpty(request)) { continue; } BitNoticeMessage msg = JsonConvert.DeserializeObject <BitNoticeMessage>(request); msg.Sender = SSOClient.UserId.ToString(); switch (msg.MessageType) { case "notice": //通知消息 LogHelper.SaveLog("WebSockets", "接收到通知消息:" + request); break; case "chat": //聊天消息 await SendStringAsync(msg); LogHelper.SaveLog("WebSockets", "接收到聊天消息:" + request); break; default: continue; } } }