Genral Socket Programming

A general question of oppinion really, what do you guys think is the better way to program using sockets i`m tending to lean against option 1 myself but not sure if its the most viable way to go with it. so what do you guys do mainy ?

Option 1
server sits waiting for connection
client opens socket
single transaction happens
client and server both close socket
rinse and repeat

Option 2
server sits waiting for connection
client opens socket
transaction happens

more transactions happen

sockets get cloed when application ends.

@ Nubiarn - it really depends on your application. As a rule of thumb (you know what they say about rules), I would go for option 2 especially if performance is of concern, you do not want to incur the cost of negotiating a connection every time you send a message. Of course if all you are doing is that single transaction every half an hour or 10 min then yes option 1 is definately an option.

Just to give you some more info. Setup of a TCP connection requires the following steps before you can even start sending your data

client -> SYN -> server
client <- SYN-ACK <- server
client -> ACK -> server



client -> FIN -> server
client <- ACK <- server
client <- FIN <- server
client -> ACK -> server

You see a lot of chatter to establish the connection then send your data and then more chatter to tear down the connection gracefully. That is quite a bit of overhead esp. if the middle bit, your actual data exchange is relatively small.

It all depends on how long you’re waiting between transactions. Personally, I would err on the side of opening connections more often. If your average time between transactions is more than, say, 60 seconds, I would definitely not hold the connection open.

There are a lot of things that can go wrong here, and the failure modes are frustrating and difficult to troubleshoot. Firewalls can time out connections, VPNs time out, routers time out and silently close connections, all things that your software won’t know about. Packets will mysteriously stop flowing, and you won’t know why.

The three-way TCP handshake is not very resource intensive, so don’t be afraid to do it. SSL, of course, is a whole other beast, as its handshake is very resource intensive, so if you’re using SSL, then keep the connections open longer if it will cut down on renegotiations.

Another option here is UDP, if you don’t require reliable transport. There’s no state to maintain with UDP, no setup, and no teardown. It’s an option to consider.

That is of course relative to the rate of communication and the network infrastructure that you are running on. On a small home network no problem, but larger network infrastructures can pose challenges of there own increasing connection latency to 100+ ms in some cases. But we agree that for low volume communication systems the Open-Send/Receive-Close is an option, however becareful of loosing data because of of delayed packets arriving after the RST, again a network infrastructure related issue and seldom seen in dev/test environments.

Certainly you need to know your particular environment and implement strategies that work in that environment, but I would hesitate to take on all the complexities involved in long-idle TCP sockets unless I knew it was necessary for some reason. Remember the two rules of optimization:

[ol]Don’t optimize.
(for experts only) Don’t optimize (yet)[/ol]

Often quoted, but should not imply that you take all the knowledge and experience available to us and simply ignore it just to say “I did not prematurely optimize”. Writing sensible code for your target implementation is not premature optimization. Again, I say we agree for the low traffic scenario, which I addressed in my initial response (admittedly a little to conservatively, I agree with your 60 second threshold and possibly lower, but not much), since we do not know the shape of the traffic is seems sensible to provide information on both the low and the high volume traffic.

Lets take an example, if the plan was to stream sensor data every second and that sensor data was just one or two 8 byte doubles, would the 3 x 48 byte (minimum) overhead in header data seem sensible? No, so the recommendation for that scenario would be to stay connected. If you only sent the data once every 60 seconds (as per your response) then I hope I had already established that I agree with you, open->send/recieve->close is an option.

So yes, don’t optimize prematurely, but at least write sensible code for your target system. And if that target system is not defined, make sure you identify the write questions to ask to understand what that environment is otherwise you build a solution that does not scale to the eventual production environment.

Excuse the rant, but working in an environment where we have custom code processing literally millions of requests per day, I suffer when someone fails to take this into consideration :).

1 Like

Trust me, I agree with you completely.

As the architect and programmer of software that processes millions of requests per day in facilities all around the US (if you’ve ever been to a doctor in the US, most likely, my software has handled your information at some point), I am acutely aware of environmental considerations.

1 Like

thanks godefroi and taylorza,

very insightful and way more detailed responses than i expected.

it seems to me that for a home network where the data transfer would be small and not very often then closing the socket after each transaction seems the most logical way to go, but i take on board the realisation if the system is in a different environment, where either the data transactions where large or frequent i would need to take the other approach.

In fact, you may have it just backwards. In a home network where there aren’t a lot of things to go wrong between the two devices, leaving the socket open makes a lot of sense. Just be prepared to handle exceptions when they come up, and keep in mind the #1 thing that those new to socket programming don’t realize: when one side dies (or something in the middle breaks the connection), the other side won’t know about it. There’s no way to know that something went wrong without attempting to send data across (unless you’re using TCP keepalives, which you’re almost certainly not, and which are probably not even supported on any NETMF TCP/IP stack).

how do you ‘rinse-and-repeat’ if the server closes its listening socket/port as well?

I would make the server act in such a way that it could handle either scenario:

Have the server wait for a connection, and as long as the connection is active, have it process transactions. When the client closes the socket, have the server go back to waiting for a connection.

funny you should say that, as thats exactly what i have runnng i have a spider acting as a server and a winrt metro app setup as a client using the new streamsocket syntax.

the original question was more of a umm ok this works, but i wonder what the norm is .

right…i think that is the best solution unless for some reason you want your server to broadcast to every connected client. in that case you will need to maintain a reference to the sockets created when the server accepts the connection. So it does boil down to requirements.
that said, i don’t think both the client and server ever have to close a socket…its one or the other really…

dont get to botherd with my orignal post sequence as it wasn`t a problem more of a query on other peoples approach, i could of worded it alot better to be honest. my server stays open listening for connections when a client connects that is then processed in a new thread. the clients does its thing, and it decides when to close its connection to the server. the server is always up and listening for new clients.

what i probably should have asked, is for single point to point transcations on a home network with a microcontroller acting as a server and a pc acting as a client, do people usually keep the clients socket connected or open and close it whenever required.

sorry if my original query was lacking in clarity,

@ nubiarn…got it and a good discussion regardless.

@ Nubiarn,

Another possibility would be, if the server is the board, to implement a high level WS-Service…
In that case, you wont have to take care of the packet format, socket connection, and so on. It will be managed by the framework…

Am I wrong ?

@ LouisCpro - to be honest i had not considered this, and i have no idea how i would to be frank.

Have a look at DPWS on Google. Some tutorials are available on the subject to implement web services with microframework.

It is very powerful when you do not care of low level and need consistent communication technics.

Hope this will help.