TCP Timeout Problems


I have a simple TCP client/server program but I having issues in which it times out quite often even though the server sends a response in usually 1 second or less. On the client I have a timer and a thread. I make the TCP request in the thread and have a timer that waits for the response from the thread. In the thread I have simple while loop that waits for the server to respond:


//start time out clock
time1= Ticks/60
BailOut = 0

While BailOut = 0

if TCPSocket1.IsConnected then
if TCPSocket1.BytesAvailable > 0 then
app.SolverData= TCPSocket1.ReadAll
BailOut = 1

speed = time2-time1

if speed > 20 then
app.SolverData = “TIMEOUT”
BailOut = 1

me.Sleep 150

In the main app the timer runs every second waiting for the SolverData variable to have a value. Is this the correct way to do this? Any help would be appreciated.


No, this isn’t the recommended way. The better way would be to implement the TCPSocket’s DataAvailable event, no Thread or Timer needed. In DataAvailable, call ReadAll, add it to a buffer if needed, then process it when ready and call the appropriate function to deal with it. There is no need to loop anywhere as DataAvailable will be called as needed by the main event loop.

Ok I had it that way initially. I will go back to putting it into the DataAvailable and see if that helps. I will still have to use a timer to get the data as having the app wait for data in the main thread was hanging up the program and I had no way to “sleep” the while loop like I can do in a thread. Thanks for the reply!

I don’t understand. Under the scheme I outlined, the app could not hang. Were you using a loop somewhere?

If timeouts are a concern, use a Timer that starts when the request is sent. Reset that Timer in DataAvailable and stop it when the result comes in. If the Timer fires, it would mean that no response had been received within the Timer’s Period.

Again, there is no reason for you to create a loop anywhere to get and process this data.

Hey Kem,
I did what you said and it seems to run much much better. I went back to using the DataAvailable event and two timers. One timer to process the data and other acting as a time out timer like you said. The only thing I use the thread for now is for sending the data to the server. Thanks for all your help! I might hit you up again tomorrow to make sure I am doing the server side correct…