The simple explanation is:
Short connection: Establish a connection, send a packet, close the connection
Long connection: Establish a connection, send a packet, send a heartbeat packet, send a packet, send a heartbeat packet, send a heartbeat packet ...
So with frequent data transmission, a short connection creates a TCP connection frequently, and for long connections, the same TCP connection is always used
Package Com.tree.demo.socket;import Java.io.ioexception;import Java.io.inputstream;import java.io.OutputStream; Import Java.net.serversocket;import Java.net.socket;public class Serversocketdemo {private static final int PORT = 1234;p rivate static final int buffer_size = 1024;public static void Main (string[] args) {//TODO auto-generated method Stubtry { ServerSocket ss = new ServerSocket (PORT); Socket s = ss.accept (); System.out.println ("This is the server, listen to the native" +port+ "port"); byte[] Recdata = Null;inputstream in = S.getinputstream (); OutputStream out = S.getoutputstream (); while (true) {recdata = new byte[buffer_size];int r = In.read (recdata);//int r = In.read (recdata); if (r>-1) {String data = new String (recdata), if (Data.trim (). Equals ("over")) {S.close ();} SYSTEM.OUT.PRINTLN ("reads the data sent to the client:" +data); Out.write ("This is the data that the server sends to the client:". GetBytes ()); Out.write (recdata);} else {System.out.println ("The data is read! "); S.close (); System.exit (0);//ss.close ();}}} catch (IOException e) {e.printstacktrace ();}}}
The above service-side read data is blocked, if the client does not have data to write, the server will always be blocked in that still
The client opens a telnet to test the socket program on the server, and of course you can write a socket client yourself, as follows:
Package Socket;import Java.io.ioexception;import Java.io.outputstream;import java.net.socket;import Java.net.unknownhostexception;public class Clientsocketdemo {private static final String HOST = "192.168.8.14";p rivate static final int PORT = 1234;public static void Main (string[] args) throws Unknownhostexception,ioexception {Socket client = new Socket (HOST, PORT), outputstream out = Client.getoutputstream (), and try {while (true) {thread.sleep (1000); System.out.println ("Send heartbeat Packet"); Out.write ("Sent heart beat Data package!". GetBytes ());}} catch (Exception e) {e.printstacktrace (); Out.close (); Client.close ();}}}
At the same time this is a heartbeat instance, the heartbeat as long as there is no abnormal situation, you can directly use the client connection to send the packet, do not need new socket to create the connection.
Socket long connection short connection heartbeat JAVA socket programming