public static Packet Read(Stream stream) { BinaryReader reader = new BinaryReader(stream); PacketType type = (PacketType)reader.ReadInt32(); Packet packet = null; switch (type) { case PacketType.ConnectionState: packet = new ConnectionStatePacket(); break; case PacketType.Request: packet = new RequestPacket(); break; case PacketType.Event: break; case PacketType.PlayfieldData: packet = new PlayfieldDataPacket(); break; case PacketType.PlayfieldMap: packet = new PlayfieldMapPacket(); break; case PacketType.EmpyrionState: packet = new EmpyrionStatePacket(); break; default: throw new Exception("Invalid packet type received."); } if (packet == null) { return(null); } packet.ReadData(reader); return(packet); }
protected virtual void HandleConnectionRequest(Connection connection, Packet packet) { if (packet is ConnectionStatePacket) { ConnectionStatePacket state = (ConnectionStatePacket)packet; if (state.Verify(Version)) { // Client is attempting to establish a connection with the correct version. connection.PacketReceived -= HandleConnectionRequest; connection.PacketReceived += Connection_PacketReceived; connection.Send(new ConnectionStatePacket(ConnectionStatePacket.ConnectionState.Accepted, Version)); } else { // Client is using an unsupported version. connection.Send(new ConnectionStatePacket(ConnectionStatePacket.ConnectionState.Rejected, Version)); connection.Close(); } } else { // Unexpected communication, client must be invalid. connection.Close(); } }
private void Connection_Verify(Connection connection, Packet packet) { ConnectionStatePacket state = packet as ConnectionStatePacket; if (state?.State == ConnectionStatePacket.ConnectionState.Accepted) { connection.PacketReceived -= this.Connection_Verify; connection.PacketReceived += this.Connection_PacketReceived; if (this.ConnectSuccess != null) { this.ConnectSuccess(this); } // Retry failed packets. foreach (Packet retry in this.failedPackets) { this.Send(retry); } } else { try { connection.Close(); if (this.ConnectFailure != null) { this.ConnectFailure(this); } } catch { } } }