When to close TCP socket ? (The perfect case)
I am developing a mobile application that transmit date using TCP protocol ( sockets ). What is the perfect solution ? is to open socket and send messa开发者_运维问答ge, and if I wan to send another message I need to repeat the same sequence, open>send>close ? OR, open>send>..keep the socket open..>send again>..>close ??
If I want to implements chat service such as instant messages , is it good to close the socket after each message , as the traffic is a big consideration ?
I hope the question is clear
It depends on the frequency of your messages being sent through the wire. If you plan to send one message every second or two, you should keep the connection open. This is how XMPP protocol works - by streaming XML one piece at a time via open TCP connection.
Keeping your connection open has two advantages: first establishing a connection comes with a price. Secondly, due to TCP/IP slow-start feature opening and closing the connection will never allow you to use close to full network bandwidth.
On the other hand if you keep the connection for too long and without any socket traffic, some network middleware like routers or firewalls might close your connection assuming it is dead. You have to consider this and either use keep-alive features or handle reconnects decently.
精彩评论