public static void ChatHandler(StateObject state, Socket handler) { Console.WriteLine("Received 'Chat' Message from {0}:{1}", ((IPEndPoint)handler.RemoteEndPoint).Address, ((IPEndPoint)handler.RemoteEndPoint).Port); ClientChatPacket dataReceived = GetChatPacketFromBytes(state.buffer); //Broadcast the message to the rest of the players Broadcast(ConnectionType.TCP, GetBytesFromPacket(dataReceived)); }
static ClientChatPacket GetChatPacketFromBytes(byte[] buffer) { ClientChatPacket packet = new ClientChatPacket(); int size = Marshal.SizeOf(packet); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.Copy(buffer, 0, ptr, size); packet = (ClientChatPacket)Marshal.PtrToStructure(ptr, packet.GetType()); Marshal.FreeHGlobal(ptr); return(packet); }
static byte[] GetBytesFromPacket(ClientChatPacket packet) { int size = System.Runtime.InteropServices.Marshal.SizeOf(packet); byte[] bytes = new byte[size]; IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(packet, ptr, true); Marshal.Copy(ptr, bytes, 0, size); Marshal.FreeHGlobal(ptr); return(bytes); }