Beispiel #1
0
        /// <summary>
        /// Receive a message from the connected client, and delegates it to listeners.
        /// </summary>
        /// <returns>Received NetworkMessage.</returns>
        private NetworkMessage StreamToMessage()
        {
            // Read message length
            byte[] lBytes = new byte[4];
            clientStream.Read(lBytes, 0, 4);
            int l = BytesToInt(lBytes);

            // Read message
            byte[] bytes = new byte[l];
            clientStream.Read(bytes, 0, bytes.Length);

            // Deserialize message
            string         data    = Encoding.UTF8.GetString(bytes);
            NetworkMessage message = null;

            try
            {
                message = NetworkMessageReader.Deserialize(data);
            }
            catch (Exception exc)
            {
                Console.WriteLine("Skipped null message");
                return(null);
            }

            // Delegate event.
            if (OnMessageReceived != null)
            {
                OnMessageReceived.Invoke(this, message);
            }

            List <Action <NetworkMessage> > actionList;

            if (eventList.TryGetValue(message.Message, out actionList))
            {
                foreach (Action <NetworkMessage> action in actionList)
                {
                    action.Invoke(message);
                }
            }

            return(message);
        }
Beispiel #2
0
    /// <summary>
    /// Checks if the server sent any message.
    /// </summary>
    private void ReceiveMessages()
    {
        // The client is null or not connected anymore
        // Stop running the thread
        if (client == null || !client.Connected)
        {
            runningThread = false;
            return;
        }

        while (stream.DataAvailable)
        {
            // Try to read the message.
            try
            {
                byte[] lBytes = new byte[4];
                stream.Read(lBytes, 0, 4);
                int    l     = BytesToInt(lBytes);
                byte[] bytes = new byte[l];

                stream.Read(bytes, 0, bytes.Length);
                // Log data.
                string         data           = Encoding.UTF8.GetString(bytes);
                NetworkMessage networkMessage = NetworkMessageReader.Deserialize(data);

                if (networkMessage == null)
                {
                    Debug.LogError("The received message object could not be deserialized to NetworkMessage.");
                    return;
                }

                AddReceivedMessages(networkMessage);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }