Esempio n. 1
0
        private void MessageProtocol_MessageComplete(byte[] bytes, int size)
        {
            var message = MessageBase.Receive(bytes, size);

            if (MessageReceived != null)
            {
                MessageReceived(message);
            }
        }
    // Read data from the server
    private void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            StateObject state  = (StateObject)ar.AsyncState;
            Socket      client = state.workSocket;

            // Read the socket
            if (client.Connected)
            {
                int bytesRead = client.EndReceive(ar);

                // Deserialize objects
                foreach (MessageBase msg in MessageBase.Receive(client, bytesRead, state))
                {
                    // Add objects to the message queue
                    lock (this.messageQueue)
                        this.messageQueue.Enqueue(msg);
                }

                // Notify any event handlers
                if (DataRecieved != null)
                {
                    DataRecieved(client, null);
                }

                // Asynchronously read more server data
                client.BeginReceive(state.Buffer, state.readOffset, state.BufferSize - state.readOffset, 0,
                                    ReceiveCallback, state);
            }
            else
            {
                Reconnect();
            }
        }
        catch (SocketException)
        {
            // Attempt server reconnect
            Reconnect();
        }
    }
    // Read data from the client
    private void ReadCallback(IAsyncResult ar)
    {
        StateObject state  = (StateObject)ar.AsyncState;
        Socket      socket = state.workSocket;

        try
        {
            if (socket.Connected)
            {
                // Read the socket
                int bytesRead = socket.EndReceive(ar);

                // Deserialize objects
                foreach (MessageBase msg in MessageBase.Receive(socket, bytesRead, state))
                {
                    // Add objects to the message queue
                    lock (this.messageQueue)
                        messageQueue.Enqueue(msg);
                }

                // Notify any event handlers
                if (DataRecieved != null)
                {
                    DataRecieved(socket, bytesRead);
                }

                // Asynchronously read more client data
                socket.BeginReceive(state.Buffer, state.readOffset, state.BufferSize - state.readOffset, 0,
                                    ReadCallback, state);
            }
            else
            {
                HandleClientDisconnect(socket);
            }
        }
        catch (SocketException)
        {
            HandleClientDisconnect(socket);
        }
    }