示例#1
0
        /// <summary>
        /// Creates web socket message from model and sends to specified client
        /// </summary>
        public static async Task SendAsync <TModel>(this SocketBase socket, TModel model, IModelWriter writer) where TModel : ISerializableModel
        {
            WebSocketMessage message = new WebSocketMessage
            {
                OpCode  = SocketOpCode.UTF8,
                Content = new MemoryStream(Encoding.UTF8.GetBytes(writer.Serialize(model)))
            };

            await socket.SendAsync(await _writer.Create(message));
        }
示例#2
0
        /// <summary>
        /// Process websocket message
        /// </summary>
        private async Task ProcessMessage(IConnectionInfo info, SocketBase socket, WebSocketMessage message)
        {
            switch (message.OpCode)
            {
            case SocketOpCode.Binary:
            case SocketOpCode.UTF8:
                //if user makes a mistake in received method, we should not interrupt connection handling
                try
                {
                    await _handler.Received(_server, info, (WsServerSocket)socket, message);
                }
                catch (Exception e)
                {
                    if (_server.Logger != null)
                    {
                        _server.Logger.LogException("Unhandled Exception", e);
                    }
                }

                break;

            //close the connection if terminate requested
            case SocketOpCode.Terminate:
                info.Close();
                break;

            //if client sends a ping message, response with pong
            case SocketOpCode.Ping:
                await socket.SendAsync(PredefinedMessages.PONG);

                break;

            //client sent response pong to ping message
            case SocketOpCode.Pong:
                socket.KeepAlive();
                break;
            }
        }