This is how I handle a TCP server setup, this is from a test project that I made to get this figured out a while back. There may be better ways to do this and there are definitely worse ways. It does make use of pointers and pointer tables so that may scare some off.
I have attached an archive of the project below. Also below, are screenshots of the two charts that are in it for those that don’t want to download and look at the project.
Here is the “Server” chart that is solely responsible for accepting connections. The transmitting and receiving are handled by a separate chart called “ProcessClient”. There is a Powerup chart that only starts the “Server” chart, which in turn starts the “ProcessClient” chart once the comm handles are configured.
This chart initializes the comm handles, and loops between ListenForIncomingCommunication and AcceptIncomingCommunication. When it detects a client connection, the chart retrieves some connection info (IP and port) for reference purposes (not needed) and flags a table that we have a connected client for the “ProcessClient” chart. Once we have a comm handle connected to a client, it gets the next available comm handle and starts listening for another client. This project is setup to handle four simultaneous clients, but it is simple to increase this if needed.
Here is the very simple ProcessClient chart.
It contains the following logic:
for nPCClient=0 to 3 step 1
//loop through clients and process
if(ntConnectedClients[nPCClient] <> 0) then
//Check for characters
//Get comm handle
pchPCTCPListen = ptchTCPListen[nPCClient];
nPCCharCount = GetNumCharsWaiting(*pchPCTCPListen);
if(nPCCharCount < 0) then
//lost connection
ntConnectedClients[nPCClient] = 0;
Output[nPCClient] = "";
elseif(nPCCharCount > 0) then
//get chars and output
ReceiveNChars(sPCBuffer, nPCCharCount, *pchPCTCPListen);
Output[nPCClient] = Output[nPCClient] + sPCBuffer;
endif
endif
next
In this case it loops through all the connected clients, checks for data, receives it and writes it to a string table. If the client disconnects, then it updates the connected clients table so that the server chart knows that the comm handles is available for future clients.
This is a simple example (it doesn’t even respond to the client) and to make it do something useful, you will need to handle all your “protocol” logic and response inside the lower else block that begins with the //get chars and output comment. Personally, I would call a subroutine at that point, or if the response may have high latency, buffer the request and have another chart handle the “protocol” which then buffers the response for the ProcessClient to send back when it is ready. This would allow the communication to be as asynchronous as possible with minimal blocking.
TCPServer.Archive.D09112024.T104504.zip (7.0 KB)