/// <summary> /// Attempts to read a whole message from fromstream /// </summary> /// <param name="fromstream"></param> /// <returns></returns> public static void ReadStreamToMessageStream(MemoryBuffer fromstream, out ChatMessage message) { message = null; //check that we have at least 4 bytes in the buffer, it contains the length of the message if (fromstream.Length > 4) { byte[] lenbuf = new byte[4]; var peeklen = fromstream.Peek(lenbuf, 0, lenbuf.Length); if (peeklen == 4) { //check that we have the whole message in the buffer var messagelength = BitConverter.ToInt32(lenbuf, 0); if (fromstream.Length >= messagelength + 4) { var messagebuffer = new byte[messagelength]; //clear the length from the buffer fromstream.Read(lenbuf, 0, lenbuf.Length); //read the message from the buffer fromstream.Read(messagebuffer, 0, messagelength); var messagestream = new MemoryStream(messagebuffer, 0, messagelength); message = DecodeMessage(messagestream); } } } }
/// <summary> /// Attempt to send a message to the client if its still connected. /// </summary> public static void SendChatMessage(TcpClient client, Stream clientStream, string message) { ChatMessage chatmessage = new ChatMessage { Message = message }; var messagestream = Common.GetStreamFromMessage(chatmessage); if (client.Connected) { var clientstream = clientStream; byte[] messagebuffer = messagestream.ToArray(); clientstream.Write(messagebuffer, 0, messagebuffer.Length); } }