1 Concepts
Socket:socket is actually an encapsulation of TCP/IP, and we can use socket sockets to transmit through the socket. The first thing we need to understand is that the channel is simply a channel that is two pairs of channels that can transmit data at any time. What I often call the establishment of a socket connection, that is, the establishment of the client and server side of the channel.
Short-to-long connection: it is obvious that this socket connection is always connected, that is, the channel has been kept unobstructed, two pairs of terminals can send and receive data at any time; the socket channel is closed when we send it once or a limited number of times. First of all, we must understand that after the socket connection, if no one is closed, the channel is maintained, in other words, if either side does not close the connection, the socket connection is a long connection, So the socket in Java itself is to support long-connected (such as a simple experiment: The server side does not shut down the connection, the server side every 10 seconds to send data, the server can receive the data correctly each time, this experiment can prove).
So since the socket itself supports long connections, why do we have to mention the concept of short connections? Imagine a China Mobile SMS gateway (that is, by releasing the socket Communication interface) every time every minute there are more than n connections to send SMS requests, join the server without any restrictions directly and the client to use long connections so imagine how much pressure the server needs to endure. So the general socket server will be set time-out, that is, timeout, if more than the timeout server did not receive any data, then the server will shut down the connection, so that the server resources are effectively used.
2 How to achieve long-term connection
In 1 we have introduced the concept of long-and long-term connection, if the server exceeds the timeout time to receive the communication of the client will be disconnected, if the client in a second (or less time) before the timeout time to send an activation data to the server to re-timer, This repetition ensures that the server has not been able to enter timeout time, and thus remains connected, which is the implementation principle of the long connection. Below we are illustrated by a diagram:
It is visible whether a long connection depends entirely on whether the client will send a heartbeat message at timeout time, so the length-to-end connection is client-related and there is no difference on the server side (except that the server side needs to set timeout).
Code implementation can be referenced by: http://download.csdn.net/detail/feichenwangyalin/7951457
Java for socket long connections and short connections