public void StartReaderWorker(RLocalClient client, RunWorkerCompletedEventHandler PacketHandler) { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler((object sender, DoWorkEventArgs eargs) => { byte[] bytes = null; ReadBytes(client, out bytes); if (bytes == null) { return; } RLocalIncomingMessage message = new RLocalIncomingMessage(); message.bytes = bytes; message.playerId = client.playerId; message.type = BitConverter.ToInt32(bytes, 0); eargs.Result = message; }); worker.RunWorkerCompleted += PacketHandler; worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((object sender, RunWorkerCompletedEventArgs e) => { if (e.Result == null) { return; } worker.RunWorkerAsync(); }); worker.RunWorkerAsync(); }
public void ReadBytes(RLocalClient client, out byte[] bytes) { try { client.stream.Read(ReadBuffer, 0, 8); int sizeOfPacket = BitConverter.ToInt32(ReadBuffer, 4); if (ReadBuffer.Length < 8 + sizeOfPacket) { Array.Resize <byte>(ref ReadBuffer, 8 + sizeOfPacket); } int amountRead = 0; while (amountRead < sizeOfPacket) { amountRead += client.stream.Read(ReadBuffer, amountRead + 8, sizeOfPacket - amountRead); } bytes = new byte[8 + amountRead]; Array.Copy(ReadBuffer, bytes, 8 + amountRead); } catch { bytes = null; m_clients.Remove(client); } }
public void StartClient(IPAddress host, int port, RunWorkerCompletedEventHandler PacketHandler) { isServer = false; var client = new TcpClient(host.ToString(), port); m_client = BuildClient(client, 0); StartReaderWorker(m_client, PacketHandler); }
public RLocalClient BuildClient(TcpClient tcpClient, int playerId) { var client = new RLocalClient(); client.tcp = tcpClient; client.stream = tcpClient.GetStream(); client.playerId = playerId; return(client); }
public void StartServer(IPAddress address, int port, RunWorkerCompletedEventHandler ReceiveClient) { isServer = true; m_server = new TcpListener(address, port); m_server.Start(); var worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler((object sender, DoWorkEventArgs eargs) => { RLocalClient client = ReceiveNextClient(); eargs.Result = client; }); worker.RunWorkerCompleted += ReceiveClient; worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((object sender, RunWorkerCompletedEventArgs e) => { worker.RunWorkerAsync(); }); worker.RunWorkerAsync(); }