/// <summary> /// 接收消息 /// </summary> public async Task ReceiveMessageAsync() { ArraySegment <byte> abuf = new ArraySegment <byte>(new byte[10240]); byte[] buf = new byte[10240]; WebSocketReceiveResult wsdata = null; string message = string.Empty; try { try { // 开始异步接收数据 wsdata = await WebSocket.ReceiveAsync(abuf, cancel); } catch (WebSocketException ex) { if (ex.InnerException is HttpListenerException) { Console.WriteLine($"{ID}客户端断开连接"); await WebSocketCloseAsync(WebSocketCloseStatus.ProtocolError, GetExceptionMessage(ex)); return; } else { Console.WriteLine($"{ID}WebSocket 连接异常。原因:{GetExceptionMessage(ex)}"); await WebSocketCloseAsync(WebSocketCloseStatus.ProtocolError, GetExceptionMessage(ex)); return; } } if (wsdata.CloseStatus.HasValue) { Console.WriteLine($"{ID}接受到关闭消息"); await WebSocketCloseAsync(wsdata.CloseStatus.Value, wsdata.CloseStatusDescription); } else { byte[] bRec = new byte[wsdata.Count]; Array.Copy(abuf.ToArray(), bRec, wsdata.Count); if (WebSocketContextHandler.BeforeReceiveHandler(this, abuf)) { message = Encoding.UTF8.GetString(bRec); WebSocketContextHandler.AflterReceiveHandler(this, message); } Console.WriteLine($"{ID}接受到消息:{message}"); await ReceiveMessageAsync(); } } catch (Exception ex) { Console.WriteLine(ex); return; } }
/// <summary> /// 发送消息 /// </summary> /// <param name="message"></param> /// <returns></returns> public async Task SendMessageAsync(string message) { if (WebSocketContextHandler.BeforeSendHandler(this, message)) { Console.WriteLine($"{ID}发送消息:{message}"); await WebSocket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(message)), WebSocketMessageType.Text, true, cancel); WebSocketContextHandler.AflterSendHandler(this, message); } }
/// <summary> /// WebSocket关闭 /// </summary> /// <param name="webSocketCloseStatus">指示关闭 WebSocket 连接的原因</param> /// <param name="statusDescription">指定一个可读的解释为连接关闭的原因。</param> public async Task WebSocketCloseAsync(WebSocketCloseStatus webSocketCloseStatus, string statusDescription) { Console.WriteLine($"{ID}WebSocket关闭"); string message = statusDescription; message = message.Length > 61 ? message.Substring(0, 61) : message; await WebSocket.CloseAsync(webSocketCloseStatus, message, new CancellationToken()); WebSocketContextHandler.CloseWebStocketHandler(this, webSocketCloseStatus, statusDescription); }