Exemple #1
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            var state = (SocketState)ar.AsyncState;


            int bytesRead = state.Client.EndReceive(ar);

            if (bytesRead <= 0)
            {
                System.Console.WriteLine("Client disconnected!");
                return;
            }

            state.Read += bytesRead;

            string received = null;

            Console.WriteLine($" ~ Receive callback! Bytes read: {bytesRead}, Available: {state.Client.Available}");

            // var received = Encoding.UTF8.GetString(state.Buffer, 0, bytesRead);
            if (this.HandShake)
            {
                if (WebSocketHandler.IsCancelFrame(state.Buffer, state.Read))
                {
                    Console.WriteLine("Client disconneted!");
                    this.Server?.EmitDisconnected(this);
                    return;
                }

                var messages = WebSocketHandler.HandlePacket(state.Buffer, state.Read);
                foreach (var message in messages)
                {
                    this.Server?.EmitMessageReceived(this, message);
                    System.Console.WriteLine($"> Received data: {message}");
                }

                if (messages.Count > 0)
                {
                    Console.WriteLine("Clearing state...");
                    state.Clear();
                    bytesRead = 0;
                }
            }
            else
            {
                received = Encoding.UTF8.GetString(state.Buffer, 0, state.Read);
                if (Regex.IsMatch(received, "^GET", RegexOptions.IgnoreCase) && received.Contains("Key"))
                {
                    System.Console.WriteLine("> Handshake started!");
                    WebSocketHandler.HandleHandshake(received, this);
                    this.HandShake = true;

                    Console.WriteLine("Clearing state...");
                    state.Clear();
                    bytesRead = 0;
                }
            }

            state.Client.BeginReceive(state.Buffer, bytesRead, SocketState.DEFAULT_BUFFER_SIZE - state.Read, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
        }