private void HandleClientComm(object client) { var tcpClient = (TcpClient)client; //tcpClient.ReceiveTimeout = 2; NetworkStream clientStream = tcpClient.GetStream(); var ms = new MemoryStream(); var binaryWriter = new BinaryWriter(ms); var message = new byte[tcpClient.ReceiveBufferSize]; var message2 = new byte[4]; int readCount; int totalReadMessageBytes = 0; clientStream.Read(message2, 0, 4); int messageLength = CommandUtils.BytesToInt(message2); while ((readCount = clientStream.Read(message, 0, tcpClient.ReceiveBufferSize)) != 0) { binaryWriter.Write(message, 0, readCount); totalReadMessageBytes += readCount; if (totalReadMessageBytes >= messageLength) { break; } } if (ms.Length > 0) { MessageAccepted(ms.ToArray(), tcpClient); } }
public void HandleServerResponse(object server) { /** Алгоритм: * Определить тип сообщения * в зависимости от этого, * распарсить байты сообщения (подойдет Dictionary с методами FromStream.) * предпринять действия * отправить ответ. * * * * */ var tcpClient = (System.Net.Sockets.TcpClient)server; tcpClient.ReceiveTimeout = 3; NetworkStream clientStream = tcpClient.GetStream(); var ms = new MemoryStream(); var binaryWriter = new BinaryWriter(ms); var messageLengthBytes = new byte[4]; var messageBytes = new byte[tcpClient.ReceiveBufferSize]; int readCount; int totalReadMessageBytes = 0; clientStream.Read(messageLengthBytes, 0, sizeof(int)); int messageLength = CommandUtils.BytesToInt(messageLengthBytes); while ((readCount = clientStream.Read(messageBytes, 0, tcpClient.ReceiveBufferSize)) != 0) { binaryWriter.Write(messageBytes, 0, readCount); totalReadMessageBytes += readCount; if (totalReadMessageBytes >= messageLength) { break; } } if (ms.Length > 0) { ParseResponseBytes(ms.ToArray()); } void ParseResponseBytes(byte[] bytes) { if (bytes.Length >= ClientCommandHeader.GetLength()) { } } }