private void HandleServerComm(object server) { TcpClient tcpClient = (TcpClient)server; NetworkStream clientStream = tcpClient.GetStream(); //Logger.ShowMessage(String.Format("Client connected on {0}, waiting for data.", tcpClient.Client.RemoteEndPoint)); byte[] message = new byte[4096]; int bytesRead; while (true) { bytesRead = 0; try { // Blocks until client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch { // Socket error occurred //Logger.ShowMessage("Could not read data from the client.", LogType.ERROR); break; } Opcode opcode = new Opcode(); // Set the opcode + the data opcode.opcode = (ClientMessage)message[0]; opcode.data = message.Where(b => b != message[0]).ToArray(); // Pack the byte array byte[] data = new byte[bytesRead]; Buffer.BlockCopy(opcode.data, 0, data, 0, bytesRead); // DEBUG /*string showBitStream = ""; foreach (byte receivedByte in data) { showBitStream += Convert.ToString(receivedByte, 2).PadLeft(8, '0'); } Logger.ShowMessage(showBitStream);*/ // DEBUG.END // Let the packetmanager invoke the correct handler PacketManager.InvokeHandler(ref mainForm, opcode.opcode, data); } }
/// <summary> /// Get the server port. /// </summary> /// <param name="server"></param> private void HandleServerComm(object server) { TcpClient tcpClient = (TcpClient)server; NetworkStream clientStream = tcpClient.GetStream(); Logger.ShowMessage(String.Format("Waiting for data.")); byte[] message = new byte[4096]; int bytesRead; while (true) { bytesRead = 0; try { // Blocks until client sends a message bytesRead = clientStream.Read(message, 0, 4096); } catch { // Socket error occurred Logger.ShowMessage("Could not read data from the server.", LogType.ERROR); break; } Opcode opcode = new Opcode(); // Set the opcode + the data opcode.opcode = (ClientMessage)message[0]; opcode.data = message.Where(b => b != message[0]).ToArray(); // Pack the byte array byte[] data = new byte[bytesRead]; Buffer.BlockCopy(opcode.data, 0, data, 0, bytesRead); // DEBUG string showBitStream = ""; foreach (byte receivedByte in data) { showBitStream += Convert.ToString(receivedByte, 2).PadLeft(8, '0'); } Logger.ShowMessage(showBitStream); // DEBUG.END ASCIIEncoding encoding = new ASCIIEncoding(); //packet = SENDER|MESSAGE int port = int.Parse(encoding.GetString(opcode.data)); // Add the client to our list. serverData serverStruct = new serverData { Server = (TcpClient)server, ServerPort = port, ClientsConnected = 0 }; Servers.Add(serverStruct); Logger.ShowMessage(String.Format("Server connected on {0}:{1}", ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address, port)); } }