private unsafe void ReadCallback(IAsyncResult ar) { State = (TCP_StateConnection)ar.AsyncState; try { Socket handler = State.workSocket; int read = handler.EndReceive(ar); var packetBuffer = new CCompoundBuffer(State.recvBuffer); if (read == 0) { OnDisconnect?.Invoke(this, EventArgs.Empty); return; } lock (_locker) { while (packetBuffer.Offset < read) { PacketSecurity.Decrypt(packetBuffer); int size = packetBuffer.ReadNextShort(0); int packetId = packetBuffer.ReadNextShort(4); if (size < 12) { break; } byte[] buffer = new byte[size]; fixed(byte *pBuffer = &packetBuffer.RawBuffer[packetBuffer.Offset]) { Marshal.Copy((IntPtr)pBuffer, buffer, 0, size); } InterpretPacket(packetId, buffer); packetBuffer.Offset += size; } } StartReceive(State); } catch (SocketException e) { throw e; } catch (Exception e) { throw e; } }
private void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); // Create the state object. State = new TCP_StateConnection { workSocket = client }; // Envia o pacote de HelloWorld e espera até 3 segundos para a resposta Send(BitConverter.GetBytes(NetworkBasics.INIT_CODE)); InitCodeEvent.WaitOne(3000); StartReceive(State); }
private void StartReceive(TCP_StateConnection state) { state.workSocket.BeginReceive(state.recvBuffer, 0, NetworkBasics.MAX_PACKET_LENGTH, 0, new AsyncCallback(ReadCallback), state); }