private static async Task HandleMessage(System.Net.WebSockets.WebSocket webSocket) { //Gets the current WebSocket object. /*We define a certain constant which will represent * size of received data. It is established by us and * we can set any value. We know that in this case the size of the sent * data is very small. */ const int maxMessageSize = 1024; //Buffer for received bits. var receivedDataBuffer = new ArraySegment <Byte>(new Byte[maxMessageSize]); var cancellationToken = new CancellationToken(); WebSocketHelper webSocketHandler = new WebSocketHelper(webSocket, /*webSocketContext, */ cancellationToken); var messageHandler = WebSocketConfig.WebSocketMessageHandlerFunc.Invoke(); while (webSocket.State == WebSocketState.Open) { //var incoming = await this._socket.ReceiveAsync(seg, CancellationToken.None); //var outgoing = new ArraySegment<byte>(buffer, 0, incoming.Count); //await this._socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None); //Reads data. WebSocketReceiveResult webSocketReceiveResult = await webSocket.ReceiveAsync(receivedDataBuffer, cancellationToken); //If input frame is cancelation frame, send close command. if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close) { if (WebSocketConfig.WebSocketMessageHandlerFunc != null) { await messageHandler.OnDisConnected(webSocketHandler);//调用MessageHandler } await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancellationToken); } else { byte[] payloadData = receivedDataBuffer.Array .Where(b => b != 0) .Take(webSocketReceiveResult.Count) .ToArray(); if (WebSocketConfig.WebSocketMessageHandlerFunc != null) { //Because we know that is a string, we convert it. string receiveString = //System.Text.Encoding.UTF8.GetString(payloadData, 0, payloadData.Length); System.Text.Encoding.UTF8.GetString(payloadData, 0, payloadData.Length); try { ReceivedMessage receivedMessage; try { receivedMessage = new ReceivedMessage() { Message = receiveString// + " | 系统错误:" + e.Message }; receivedMessage = Newtonsoft.Json.JsonConvert.DeserializeObject <ReceivedMessage>(receiveString); } catch (Exception e) { receivedMessage = new ReceivedMessage() { Message = receiveString// + " | 系统错误:" + e.Message }; } await messageHandler.OnMessageReceiced(webSocketHandler, receivedMessage, receiveString);//调用MessageHandler } catch (Exception ex) { } } } } }
/// <summary> /// 收到消息时触发事件 /// </summary> /// <param name="webSocketHandler"></param> /// <param name="message">封装好的数据</param> /// <param name="originalData">原始数据字符串</param> /// <returns></returns> public abstract Task OnMessageReceiced(WebSocketHelper webSocketHandler, ReceivedMessage message, string originalData);