/// <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);
Пример #2
0
        /// <summary>
        /// 部分Handler过程参考:http://www.cnblogs.com/lookbs/p/MVC-IMG.html
        /// </summary>
        /// <param name="webSocketContext"></param>
        /// <returns></returns>
        public static async Task WebSocketRequestHandler(AspNetWebSocketContext webSocketContext)
        {
            //Gets the current WebSocket object.
            System.Net.WebSockets.WebSocket webSocket = webSocketContext.WebSocket;

            /*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(webSocketContext, cancellationToken);
            var             messageHandler   = WebSocketConfig.WebSocketMessageHandlerFunc.Invoke();

            if (webSocket.State == WebSocketState.Connecting)
            {
                if (WebSocketConfig.WebSocketMessageHandlerFunc != null)
                {
                    await messageHandler.OnConnecting(webSocketHandler);//调用MessageHandler
                }
            }

            //Checks WebSocket state.
            while (webSocket.State == WebSocketState.Open)
            {
                //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);
                        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)
                        {
                        }
                    }
                }
            }
        }
Пример #3
0
        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).ConfigureAwait(false);

                //If input frame is cancelation frame, send close command.
                if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
                {
                    if (WebSocketConfig.WebSocketMessageHandlerFunc != null)
                    {
                        await messageHandler.OnDisConnected(webSocketHandler).ConfigureAwait(false);//调用MessageHandler
                    }

                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,
                                               String.Empty, cancellationToken).ConfigureAwait(false);
                }
                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
                                };


#if NET45
                                JavaScriptSerializer js = new JavaScriptSerializer();
                                receivedMessage = js.Deserialize <ReceivedMessage>(receiveString);
#else
                                receivedMessage = Newtonsoft.Json.JsonConvert.DeserializeObject <ReceivedMessage>(receiveString);
#endif
                            }
                            catch (Exception e)
                            {
                                receivedMessage = new ReceivedMessage()
                                {
                                    Message = receiveString// + " | 系统错误:" + e.Message
                                };
                            }
                            await messageHandler.OnMessageReceiced(webSocketHandler, receivedMessage, receiveString).ConfigureAwait(false);//调用MessageHandler
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            }
        }