BlottoBeats.Library.Networking.Message.Recieve C# (CSharp) Method

Recieve() public static method

Receieves a single object over the specified stream
public static Recieve ( NetworkStream stream ) : object
stream System.Net.Sockets.NetworkStream Stream to receive the message from
return object
        public static object Recieve(NetworkStream stream)
        {
            int dataLength;
            byte[] data = new byte[sizeof(Int32)];

            int bytesRead = 0;
            int totalBytesRead = 0;

            try {
                // Read the length integer
                do {
                    bytesRead = stream.Read(data, totalBytesRead, (data.Length - totalBytesRead));
                    totalBytesRead += bytesRead;
                } while (totalBytesRead < sizeof(Int32) && bytesRead != 0);

                if (totalBytesRead < sizeof(Int32)) {
                    if (totalBytesRead != 0) Console.Error.WriteLine("Message Recieve Failed: connection closed unexpectedly");
                    return null;
                }

                if (BitConverter.IsLittleEndian) Array.Reverse(data);
                dataLength = BitConverter.ToInt32(data, 0);

                if (dataLength == 0) {
                    // A test message was sent.
                    return "Test";
                } else {
                    data = new byte[dataLength];

                    // Read data until the client disconnects
                    totalBytesRead = 0;
                    do {
                        bytesRead = stream.Read(data, totalBytesRead, (dataLength - totalBytesRead));
                        totalBytesRead += bytesRead;
                    } while (totalBytesRead < dataLength && bytesRead != 0);

                    if (totalBytesRead < dataLength) {
                        Console.Error.WriteLine("Message Receive Failed: connection closed unexpectedly");
                        return null;
                    }

                    return Unpack(data);
                }
            } catch (Exception e) {
                Console.Error.WriteLine("A socket error has occured: " + e.ToString());
                return null;
            }
        }

Usage Example

Example #1
0
        /// <summary>
        /// Tests a connection to see if it is valid
        /// </summary>
        /// <param name="stream">Stream to test</param>
        /// <returns>True if the connection is valid, false otherwise</returns>
        public static bool Test(NetworkStream stream)
        {
            Message.TestMsg(stream);
            object response = Message.Recieve(stream);

            return(response is string && "Test" == (string)response);
        }
All Usage Examples Of BlottoBeats.Library.Networking.Message::Recieve