#include <tnlNetConnection.h>
Inheritance diagram for TNL::NetConnection:
NetConnection is the base class for the connection classes in TNL. It implements a notification protocol on the unreliable packet transport of UDP (via the TNL::Net layer). NetConnection manages the flow of packets over the network, and calls its subclasses to read and write packet data, as well as handle packet delivery notification.
Because string data can easily soak up network bandwidth, for efficiency NetConnection implements an optional networked string table. Users can then notify the connection of strings it references often, such as player names, and transmit only a tag, instead of the whole string.
Adaptive Protocol | |
Functions and state for the adaptive rate protocol. TNL's adaptive rate uses rate control algorithms similar to TCP/IP's.
There are a few state variables here that aren't documented. | |
void | setIsAdaptive () |
Enables the adaptive protocol. | |
void | setFixedRateParameters (U32 minPacketSendPeriod, U32 minPacketRecvPeriod, U32 maxSendBandwidth, U32 maxRecvBandwidth) |
sets the fixed rate send and receive data sizes, and sets the connection to not behave as an adaptive rate connection | |
bool | isAdaptive () |
Query the adaptive status of the connection. | |
virtual bool | isDataToTransmit () |
Returns true if this connection has data to transmit. | |
F32 | cwnd |
F32 | ssthresh |
U32 | mLastSeqRecvdAck |
U32 | mLastAckTime |
Public Types | |
enum | TerminationReason { ReasonTimedOut, ReasonFailedConnectHandshake, ReasonRemoteHostRejectedConnection, ReasonRemoteDisconnectPacket, ReasonDuplicateConnectionAttempt, ReasonSelfDisconnect, ReasonError } |
enum | NetConnectionTypeFlags { ConnectionToServer = BIT(0), ConnectionToClient = BIT(1), ConnectionAdaptive = BIT(2), ConnectionRemoteAdaptive = BIT(3) } |
Flags specifying the type of the connection instance. More... | |
enum | NetConnectionState { NotConnected = 0, AwaitingChallengeResponse, SendingPunchPackets, ComputingPuzzleSolution, AwaitingConnectResponse, ConnectTimedOut, ConnectRejected, Connected, Disconnected, TimedOut, StateCount } |
Connection state flags for a NetConnection instance. More... | |
Public Member Functions | |
NetConnection () | |
~NetConnection () | |
U32 | getNextSendSequence () |
Returns the next send sequence that will be sent by this side. | |
U32 | getLastSendSequence () |
Returns the sequence of the last packet sent by this connection, or the current packet's send sequence if called from within writePacket(). | |
void | setInitialRecvSequence (U32 sequence) |
Sets the initial sequence number of packets read from the remote host. | |
U32 | getInitialRecvSequence () |
Returns the initial sequence number of packets sent from the remote host. | |
U32 | getInitialSendSequence () |
Returns the initial sequence number of packets sent to the remote host. | |
void | connect (NetInterface *connectionInterface, const Address &address, bool requestKeyExchange=false, bool requestCertificate=false) |
Connect to a server through a given network interface. | |
bool | connectLocal (NetInterface *connectionInterface, NetInterface *localServerInterface) |
Connects to a server interface within the same process. | |
void | connectArranged (NetInterface *connectionInterface, const Vector< Address > &possibleAddresses, Nonce &myNonce, Nonce &remoteNonce, ByteBufferPtr sharedSecret, bool isInitiator, bool requestsKeyExchange=false, bool requestsCertificate=false) |
Connects to a remote host that is also connecting to this connection (negotiated by a third party). | |
void | disconnect (const char *reason) |
Sends a disconnect packet to notify the remote host that this side is terminating the connection for the specified reason. | |
bool | windowFull () |
Returns true if the packet send window is full and no more data packets can be sent. | |
ConnectionParameters & | getConnectionParameters () |
bool | isInitiator () |
returns true if this object initiated the connection with the remote host | |
void | setRemoteConnectionObject (NetConnection *connection) |
NetConnection * | getRemoteConnectionObject () |
void | setInterface (NetInterface *myInterface) |
Sets the NetInterface this NetConnection will communicate through. | |
NetInterface * | getInterface () |
Returns the NetInterface this connection communicates through. | |
void | setSymmetricCipher (SymmetricCipher *theCipher) |
Sets the SymmetricCipher this NetConnection will use for encryption. | |
virtual NetClassGroup | getNetClassGroup () const |
Returns the class group of objects that can be transmitted over this NetConnection. | |
void | setPingTimeouts (U32 msPerPing, U32 pingRetryCount) |
Sets the ping/timeout characteristics for a fixed-rate connection. Total timeout is msPerPing * pingRetryCount. | |
void | setSimulatedNetParams (F32 packetLoss, U32 latency) |
Simulates a network situation with a percentage random packet loss and a connection one way latency as specified. | |
void | setIsConnectionToServer () |
Specifies that this NetConnection instance is a connection to a "server.". | |
bool | isConnectionToServer () |
Returns true if this is a connection to a "server.". | |
void | setIsConnectionToClient () |
Specifies that this NetConnection instance is a connection to a "client.". | |
bool | isConnectionToClient () |
Returns true if this is a connection to a "client.". | |
bool | isLocalConnection () |
Returns true if the remote side of this connection is a NetConnection instance in on the same host. | |
bool | isNetworkConnection () |
Returns true if the remote side if this connection is on a remote host. | |
F32 | getRoundTripTime () |
Returns the running average packet round trip time. | |
F32 | getOneWayTime () |
Returns have of the average of the round trip packet time. | |
const Address & | getNetAddress () |
Returns the remote address of the host we're connected or trying to connect to. | |
const char * | getNetAddressString () const |
Returns the remote address in string form. | |
void | setNetAddress (const Address &address) |
Sets the address of the remote host we want to connect to. | |
NetError | sendPacket (BitStream *stream) |
Sends a packet that was written into a BitStream to the remote host, or the mRemoteConnection on this host. | |
bool | checkTimeout (U32 time) |
Checks to see if the connection has timed out, possibly sending a ping packet to the remote host. Returns true if the connection timed out. | |
void | checkPacketSend (bool force, U32 currentTime) |
Checks to see if a packet should be sent at the currentTime to the remote host. | |
void | setConnectionState (NetConnectionState state) |
Sets the current connection state of this NetConnection. | |
NetConnectionState | getConnectionState () |
Gets the current connection state of this NetConnection. | |
bool | isEstablished () |
Returns true if the connection handshaking has completed successfully. | |
void | setTranslatesStrings () |
Enables string tag translation on this connection. | |
Static Public Member Functions | |
char * | getErrorBuffer () |
returns the current error buffer | |
void | setLastError (const char *fmt,...) |
Sets an error string and notifies the currently processing connection that it should terminate. | |
Data Fields | |
U32 | mConnectSendCount |
Number of challenge or connect requests sent to the remote host. | |
U32 | mConnectLastSendTime |
The send time of the last challenge or connect request. | |
NetConnectionState | mConnectionState |
Current state of this NetConnection. | |
Protected Member Functions | |
virtual void | onConnectTerminated (TerminationReason reason, const char *rejectionString) |
Called when a pending connection is terminated. | |
virtual void | onConnectionTerminated (TerminationReason, const char *errorDisconnectString) |
Called when this established connection is terminated for any reason. | |
virtual void | onConnectionEstablished () |
Called when the connection is successfully established with the remote host. | |
virtual bool | validateCertficate (Certificate *theCertificate, bool isInitiator) |
validates that the given certificate is a valid certificate for this connection. | |
virtual bool | validatePublicKey (AsymmetricKey *theKey, bool isInitiator) |
Validates that the given public key is valid for this connection. | |
virtual void | writeConnectRequest (BitStream *stream) |
Fills the connect request packet with additional custom data (from a subclass). | |
virtual bool | readConnectRequest (BitStream *stream, const char **errorString) |
Called after this connection instance is created on a non-initiating host (server). | |
virtual void | writeConnectAccept (BitStream *stream) |
Writes any data needed to start the connection on the accept packet. | |
virtual bool | readConnectAccept (BitStream *stream, const char **errorString) |
Reads out the extra data read by writeConnectAccept and returns true if it is processed properly. | |
virtual void | readPacket (BitStream *bstream) |
Called to read a subclass's packet data from the packet. | |
virtual void | prepareWritePacket () |
Called to prepare the connection for packet writing. | |
virtual void | writePacket (BitStream *bstream, PacketNotify *note) |
Called to write a subclass's packet data into the packet. | |
virtual void | packetReceived (PacketNotify *note) |
Called when the packet associated with the specified notify is known to have been received by the remote host. | |
virtual void | packetDropped (PacketNotify *note) |
Called when the packet associated with the specified notify is known to have been not received by the remote host. | |
virtual PacketNotify * | allocNotify () |
Allocates a data record to track data sent on an individual packet. | |
void | readRawPacket (BitStream *bstream) |
Reads a raw packet from a BitStream, as dispatched from NetInterface. | |
void | writeRawPacket (BitStream *bstream, NetPacketType packetType) |
Writes a full packet of the specified type into the BitStream. | |
void | writePacketHeader (BitStream *bstream, NetPacketType packetType) |
Writes the notify protocol's packet header into the BitStream. | |
bool | readPacketHeader (BitStream *bstream) |
Reads a notify protocol packet header from the BitStream and returns true if it was a data packet that needs more processing. | |
void | writePacketRateInfo (BitStream *bstream, PacketNotify *note) |
Writes any packet send rate change information into the packet. | |
void | readPacketRateInfo (BitStream *bstream) |
Reads any packet send rate information requests from the packet. | |
void | sendPingPacket () |
Sends a ping packet to the remote host, to determine if it is still alive and what its packet window status is. | |
void | sendAckPacket () |
Sends an ack packet to the remote host, in response to receiving a ping packet. | |
void | handleNotify (U32 sequence, bool recvd) |
Dispatches a notify when a packet is ACK'd or NACK'd. | |
void | keepAlive () |
Called when a packet is received to stop any timeout action in progress. | |
void | clearAllPacketNotifies () |
Clears out the pending notify list. | |
PacketNotify * | getCurrentWritePacketNotify () |
Returns the notify structure for the current packet write, or last written packet. | |
Protected Attributes | |
PacketNotify * | mNotifyQueueHead |
Linked list of structures representing the data in sent packets. | |
PacketNotify * | mNotifyQueueTail |
Tail of the notify queue linked list. New packets are added to the end of the tail. | |
SafePtr< NetConnection > | mRemoteConnection |
Safe pointer to a short-circuit remote connection on the same host. | |
ConnectionParameters | mConnectionParameters |
SafePtr< NetInterface > | mInterface |
The NetInterface of which this NetConnection is a member. | |
RefPtr< SymmetricCipher > | mSymmetricCipher |
The helper object that performs symmetric encryption on packets. | |
Static Protected Attributes | |
char | mErrorBuffer [256] |
String buffer that errors are written into. | |
Private Types | |
typedef Object | Parent |
enum | HeaderConstants { MaxPacketWindowSizeShift = 5, MaxPacketWindowSize = (1 << MaxPacketWindowSizeShift), PacketWindowMask = MaxPacketWindowSize - 1, MaxAckMaskSize = 1 << (MaxPacketWindowSizeShift - 5), MaxAckByteCount = MaxAckMaskSize << 2, SequenceNumberBitSize = 11, SequenceNumberWindowSize = (1 << SequenceNumberBitSize), SequenceNumberMask = -SequenceNumberWindowSize, AckSequenceNumberBitSize = 10, AckSequenceNumberWindowSize = (1 << AckSequenceNumberBitSize), AckSequenceNumberMask = -AckSequenceNumberWindowSize, PacketHeaderBitSize = 3 + AckSequenceNumberBitSize + SequenceNumberBitSize, PacketHeaderByteSize = (PacketHeaderBitSize + 7) >> 3, PacketHeaderPadBits = (PacketHeaderByteSize << 3) - PacketHeaderBitSize, MessageSignatureBytes = 5 } |
Constants controlling the data representation of each packet header. More... | |
enum | NetPacketType { DataPacket, PingPacket, AckPacket, InvalidPacketType } |
Two-bit identifier for each connected packet. More... | |
enum | DefaultPingConstants { AdaptiveInitialPingTimeout = 60000, AdaptivePingRetryCount = 4, DefaultPingTimeout = 5000, DefaultPingRetryCount = 10, AdaptiveUnackedSentPingTimeout = 3000 } |
Constants controlling the behavior of pings and timeouts. More... | |
enum | RateDefaults { DefaultFixedBandwidth = 2500, DefaultFixedSendPeriod = 96, MaxFixedBandwidth = 65535, MaxFixedSendPeriod = 2047 } |
Private Member Functions | |
bool | hasUnackedSentPackets () |
Returns true if this connection has sent packets that have not yet been acked by the remote host. | |
void | computeNegotiatedRate () |
Called internally when the local or remote rate changes. | |
Private Attributes | |
U32 | mLastPacketRecvTime |
Time of the receipt of the last data packet. | |
U32 | mLastSeqRecvdAtSend [MaxPacketWindowSize] |
The sequence number of the last packet received from the remote host when we sent the packet with sequence X & PacketWindowMask. | |
U32 | mLastSeqRecvd |
The sequence number of the most recently received packet from the remote host. | |
U32 | mHighestAckedSeq |
The highest sequence number the remote side has acknowledged. | |
U32 | mLastSendSeq |
The sequence number of the last packet sent. | |
U32 | mAckMask [MaxAckMaskSize] |
long string of bits, each acking a packet sent by the remote host | |
U32 | mLastRecvAckAck |
The highest sequence this side knows the other side has received an ACK or NACK for. | |
U32 | mInitialSendSeq |
The first mLastSendSeq for this side of the connection. | |
U32 | mInitialRecvSeq |
The first mLastSeqRecvd (the first mLastSendSeq for the remote host). | |
U32 | mHighestAckedSendTime |
The send time of the highest packet sequence acked by the remote host. | |
U32 | mPingTimeout |
Milliseconds to wait before sending a ping packet. | |
U32 | mPingRetryCount |
Number of unacknowledged pings to send before timing out. | |
BitSet32 | mTypeFlags |
Flags describing the type of connection this is, OR'd from NetConnectionTypeFlags. | |
U32 | mLastUpdateTime |
The last time a packet was sent from this instance. | |
F32 | mRoundTripTime |
Running average round trip time. | |
U32 | mSendDelayCredit |
Metric to help compensate for irregularities on fixed rate packet sends. | |
U32 | mSimulatedLatency |
Amount of additional time this connection delays its packet sends to simulate latency in the connection. | |
F32 | mSimulatedPacketLoss |
Function to simulate packet loss on a network. | |
NetRate | mLocalRate |
Current communications rate negotiated for this connection. | |
NetRate | mRemoteRate |
Maximum allowable communications rate for this connection. | |
bool | mLocalRateChanged |
Set to true when the local connection's rate has changed. | |
U32 | mCurrentPacketSendSize |
Current size of each packet sent to the remote host. | |
U32 | mCurrentPacketSendPeriod |
Millisecond delay between sent packets. | |
Address | mNetAddress |
The network address of the host this instance is connected to. | |
U32 | mPingSendCount |
Number of unacknowledged ping packets sent to the remote host. | |
U32 | mLastPingSendTime |
Last time a ping packet was sent from this connection. | |
ConnectionStringTable * | mStringTable |
Helper for managing translation between global NetStringTable ids to local ids for this connection. | |
Friends | |
class | NetInterface |
class | ConnectionStringTable |
|
Reimplemented in TNL::EventConnection, TNL::GhostConnection, and TNLTest::TestConnection. |
|
|
Two-bit identifier for each connected packet.
|
|
Constants controlling the behavior of pings and timeouts.
|
|
|
|
Flags specifying the type of the connection instance.
|
|
|
|
Connection state flags for a NetConnection instance.
|
|
|
|
|
|
Returns true if this connection has sent packets that have not yet been acked by the remote host.
|
|
Called when a pending connection is terminated.
|
|
Called when this established connection is terminated for any reason.
|
|
Called when the connection is successfully established with the remote host.
Reimplemented in TNLTest::TestConnection. |
|
validates that the given certificate is a valid certificate for this connection.
|
|
Validates that the given public key is valid for this connection. If this host requires a valid certificate for the communication, this function should always return false. It will only be called if the remote side of the connection did not provide a certificate. |
|
Fills the connect request packet with additional custom data (from a subclass).
Reimplemented in TNL::EventConnection. |
|
Called after this connection instance is created on a non-initiating host (server). Reads data sent by the writeConnectRequest method and returns true if the connection is accepted or false if it's not. The errorString pointer should be filled if the connection is rejected. Reimplemented in TNL::EventConnection. |
|
Writes any data needed to start the connection on the accept packet.
Reimplemented in TNL::EventConnection. |
|
Reads out the extra data read by writeConnectAccept and returns true if it is processed properly.
Reimplemented in TNL::EventConnection. |
|
Called to read a subclass's packet data from the packet.
Reimplemented in TNL::EventConnection, and TNL::GhostConnection. |
|
Called to prepare the connection for packet writing. Any setup work to determine if there isDataToTransmit() should happen in this function. prepareWritePacket should _always_ call the Parent:: function. Reimplemented in TNL::GhostConnection. |
|
Called to write a subclass's packet data into the packet. Information about what the instance wrote into the packet can be attached to the notify object. Reimplemented in TNL::EventConnection, and TNL::GhostConnection. |
|
Called when the packet associated with the specified notify is known to have been received by the remote host. Packets are guaranteed to be notified in the order in which they were sent. Reimplemented in TNL::EventConnection, and TNL::GhostConnection. |
|
Called when the packet associated with the specified notify is known to have been not received by the remote host. Packets are guaranteed to be notified in the order in which they were sent. Reimplemented in TNL::EventConnection, and TNL::GhostConnection. |
|
Allocates a data record to track data sent on an individual packet. If you need to track additional notification information, you'll have to override this so you allocate a subclass of PacketNotify with extra fields. Reimplemented in TNL::EventConnection, and TNL::GhostConnection. |
|
Returns the next send sequence that will be sent by this side.
|
|
Returns the sequence of the last packet sent by this connection, or the current packet's send sequence if called from within writePacket().
|
|
Reads a raw packet from a BitStream, as dispatched from NetInterface.
|
|
Writes a full packet of the specified type into the BitStream.
|
|
Writes the notify protocol's packet header into the BitStream.
|
|
Reads a notify protocol packet header from the BitStream and returns true if it was a data packet that needs more processing.
|
|
Writes any packet send rate change information into the packet.
|
|
Reads any packet send rate information requests from the packet.
|
|
Sends a ping packet to the remote host, to determine if it is still alive and what its packet window status is.
|
|
Sends an ack packet to the remote host, in response to receiving a ping packet.
|
|
Dispatches a notify when a packet is ACK'd or NACK'd.
|
|
Called when a packet is received to stop any timeout action in progress.
|
|
Clears out the pending notify list.
|
|
Sets the initial sequence number of packets read from the remote host.
|
|
Returns the initial sequence number of packets sent from the remote host.
|
|
Returns the initial sequence number of packets sent to the remote host.
|
|
Connect to a server through a given network interface. The connection request can require that the connection use encryption, or that the remote host's certificate be validated by a known Certificate Authority |
|
Connects to a server interface within the same process.
|
|
Connects to a remote host that is also connecting to this connection (negotiated by a third party).
|
|
Sends a disconnect packet to notify the remote host that this side is terminating the connection for the specified reason. This will remove the connection from its NetInterface, and may have the side effect that the connection is deleted, if there are no other objects with RefPtrs to the connection. |
|
Returns true if the packet send window is full and no more data packets can be sent.
|
|
Called internally when the local or remote rate changes.
|
|
Returns the notify structure for the current packet write, or last written packet.
|
|
|
|
returns true if this object initiated the connection with the remote host
|
|
|
|
|
|
returns the current error buffer
|
|
Sets an error string and notifies the currently processing connection that it should terminate.
|
|
Sets the NetInterface this NetConnection will communicate through.
|
|
Returns the NetInterface this connection communicates through.
|
|
Sets the SymmetricCipher this NetConnection will use for encryption.
|
|
Returns the class group of objects that can be transmitted over this NetConnection.
|
|
Sets the ping/timeout characteristics for a fixed-rate connection. Total timeout is msPerPing * pingRetryCount.
|
|
Simulates a network situation with a percentage random packet loss and a connection one way latency as specified.
|
|
Specifies that this NetConnection instance is a connection to a "server.".
|
|
Returns true if this is a connection to a "server.".
|
|
Specifies that this NetConnection instance is a connection to a "client.".
|
|
Returns true if this is a connection to a "client.".
|
|
Returns true if the remote side of this connection is a NetConnection instance in on the same host.
|
|
Returns true if the remote side if this connection is on a remote host.
|
|
Returns the running average packet round trip time.
|
|
Returns have of the average of the round trip packet time.
|
|
Returns the remote address of the host we're connected or trying to connect to.
|
|
Returns the remote address in string form.
|
|
Sets the address of the remote host we want to connect to.
|
|
Sends a packet that was written into a BitStream to the remote host, or the mRemoteConnection on this host.
|
|
Checks to see if the connection has timed out, possibly sending a ping packet to the remote host. Returns true if the connection timed out.
|
|
Checks to see if a packet should be sent at the currentTime to the remote host. If force is true and there is space in the window, it will always send a packet. |
|
Sets the current connection state of this NetConnection.
|
|
Gets the current connection state of this NetConnection.
|
|
Returns true if the connection handshaking has completed successfully.
|
|
Enables the adaptive protocol. By default NetConnection operates with a fixed rate protocol - that is, it sends a packet every few milliseconds, based on some configuration parameters. However, it is possible to use an adaptive rate protocol that attempts to maximize thoroughput over the connection. Calling this function enables this behavior. |
|
sets the fixed rate send and receive data sizes, and sets the connection to not behave as an adaptive rate connection
|
|
Query the adaptive status of the connection.
|
|
Returns true if this connection has data to transmit. The adaptive rate protocol needs to be able to tell if there is data ready to be sent, so that it can avoid sending unnecessary packets. Each subclass of NetConnection may need to send different data - events, ghost updates, or other things. Therefore, this hook is provided so that child classes can overload it and let the adaptive protocol function properly.
Reimplemented in TNL::EventConnection, TNL::GhostConnection, and TNLTest::TestConnection. |
|
Enables string tag translation on this connection.
|
|
|
|
|
|
Time of the receipt of the last data packet.
|
|
The sequence number of the last packet received from the remote host when we sent the packet with sequence X & PacketWindowMask.
|
|
The sequence number of the most recently received packet from the remote host.
|
|
The highest sequence number the remote side has acknowledged.
|
|
The sequence number of the last packet sent.
|
|
long string of bits, each acking a packet sent by the remote host The bit associated with mLastSeqRecvd is the low bit of the 0'th word of mAckMask. |
|
The highest sequence this side knows the other side has received an ACK or NACK for.
|
|
The first mLastSendSeq for this side of the connection.
|
|
The first mLastSeqRecvd (the first mLastSendSeq for the remote host).
|
|
The send time of the highest packet sequence acked by the remote host. Used in the computation of round trip time. |
|
Milliseconds to wait before sending a ping packet.
|
|
Number of unacknowledged pings to send before timing out.
|
|
Flags describing the type of connection this is, OR'd from NetConnectionTypeFlags.
|
|
The last time a packet was sent from this instance.
|
|
Running average round trip time.
|
|
Metric to help compensate for irregularities on fixed rate packet sends.
|
|
Amount of additional time this connection delays its packet sends to simulate latency in the connection.
|
|
Function to simulate packet loss on a network.
|
|
Current communications rate negotiated for this connection.
|
|
Maximum allowable communications rate for this connection.
|
|
Set to true when the local connection's rate has changed.
|
|
Current size of each packet sent to the remote host.
|
|
Millisecond delay between sent packets.
|
|
The network address of the host this instance is connected to.
|
|
Number of unacknowledged ping packets sent to the remote host.
|
|
Last time a ping packet was sent from this connection.
|
|
Linked list of structures representing the data in sent packets.
|
|
Tail of the notify queue linked list. New packets are added to the end of the tail.
|
|
Safe pointer to a short-circuit remote connection on the same host. This currently isn't enabled - see the end of netConnection.cpp for an example of how to use this. If it's set, the code will use short circuited networking. |
|
|
|
Number of challenge or connect requests sent to the remote host.
|
|
The send time of the last challenge or connect request.
|
|
String buffer that errors are written into.
|
|
The NetInterface of which this NetConnection is a member.
|
|
The helper object that performs symmetric encryption on packets.
|
|
Current state of this NetConnection.
|
|
|
|
|
|
|
|
|
|
Helper for managing translation between global NetStringTable ids to local ids for this connection.
|