NetBurner 3.5.6
PDF Version |
This NetBurner application demonstrates a TCP server implementation with keep-alive functionality. The server listens for incoming TCP connections and uses keep-alive packets to detect when clients become unresponsive or disconnect unexpectedly.
Keep-alive is implemented with the TcpGetLastRxTime()
and TcpSendKeepAlive()
functions. TcpGetLastRxTime()
returns the number of time ticks since the last time a packet was received. TcpSendKeepAlive()
sends a keep-alive packet to the client, which is used when no data is has been transmitted within the timeout period.
The general concept is to call TcpGetLastRxTime()
, call TcpSendKeepAlive()
, wait a bit, then call TcpSendKeepAlive()
a second time and verify the number of time ticks is different. If not, no packets were received and the client is not responding. Make sure to allow time for the client to respond to the keep alive packet. Do not call TcpGetLastRxTime more often than once every second to avoid performance issues.
The keep-alive functionality is implemented using two key NetBurner functions:
TcpGetLastRxTime()
- Returns the number of time ticks since the last received packetTcpSendKeepAlive()
- Sends a keep-alive packet to the clientThe example creates a TCP server task that listens on port 23 by default. The server blocks with "ReadWithTimeOut" until data is received or the timer times out. If a timeout occurs the time of the last received packet is recorded and a keep-alive packet is sent. Then, the server goes back to waiting for a read again. If ReadWithTimeOut times out a second time, the value of the last received TCP packet is checked again. If the client is still active the value of lastRxTime will be different than the previous value (due to the keep-alive packet that was sent). If the client did not respond to the keep-alive packet the number will remain the same and the client is assumed to be non-responsive, and the connection is closed.
ReadWithTimeout()
with a 1-second timeoutTo modify the listening port, change the TCP_LISTEN_PORT
constant:
From a Windows command prompt:
From Linux/Mac terminal:
fdListen
: Listening socket file descriptorfdNet
: Client connection file descriptorLastRxTime
: Timestamp of last received packetkeepAliveSent
: Flag to track keep-alive stateRXBuffer
: Buffer for incoming dataTcpGetLastRxTime()
more frequently than once per second to avoid performance issuesThe application provides detailed debug information including:
All debug output is sent to the NetBurner's debug/console serial port.