예제 #1
0
        public static void HandlePacket(string sockJsPacket)
        {
            var packetType = Decoder.DeterminePacketType(sockJsPacket);

            switch (packetType)
            {
            case PacketType.ConnectionOpen:
                ConnectionOpenPacketReceived?.Invoke(EventArgs.Empty);
                break;

            case PacketType.ConnectionClose:
                ConnectionClosePacketReceived?.Invoke(EventArgs.Empty);
                break;

            case PacketType.SocketHeartbeat:
                SocketHeartbeatReceived?.Invoke(DateTime.Now);
                break;

            case PacketType.SocketMessage:
                var packets = Decoder.DecodePackets(sockJsPacket);
                SocketMessageReceived?.Invoke(packets);
                break;

            case PacketType.BinaryData:
                Debug.WriteLine("Binary data not supported.");
                break;

            default:     // Includes PacketType.Invalid
                Debug.WriteLine("Invalid packet received.");
                break;
            }
        }
예제 #2
0
        public async Task ReceiveAsync()
        {
            var receiveBuffer = new byte[4096];

            while (_socket.State == WebSocketState.Open)
            {
                _logger.LogTrace(_socket.State.ToString());
                var message = new byte[4096];
                var offset  = 0;

                WebSocketReceiveResult receive;

                do
                {
                    receive = await _socket.ReceiveAsync(new ArraySegment <byte>(receiveBuffer), CancellationToken.None);

                    receiveBuffer.CopyTo(message, offset);

                    offset       += receive.Count;
                    receiveBuffer = new byte[4096];
                } while (!receive.EndOfMessage);

                if (receive.MessageType == WebSocketMessageType.Close)
                {
                    // connection closed, reconnect
                    break;
                }

                if (receive.MessageType == WebSocketMessageType.Binary)
                {
                    _logger.LogDebug(LogEvent.Receive, "Binary message received, ignoring");
                }

                if (receive.MessageType == WebSocketMessageType.Text)
                {
                    var text    = Encoding.UTF8.GetString(message);
                    var payload = JsonConvert.DeserializeObject <GatewayPayload>(text);

                    SocketMessageReceived?.Invoke(this, new SocketMessageEventArgs {
                        Content = text, Payload = payload
                    });
                }
            }

            Disconnected?.Invoke(this);
        }