Before very rarely do this pure socket programming, recently the company has a project needs to communicate with the PC, its own agreement to set the text, wrote a simple Java socket based client.
Function almost later, found a problem, to the PC end of the text, the PC end of the IP port, will have been Deng, until the everlasting. I was just beginning to think that there was a problem with the code.
Previous code:
Socket socket = NULL;
try {
Socket =new socket (host,port);//The problem is here.
Socket.setsotimeout (timeout);
I thought I set timeout: socket.setsotimeout (timeout), in fact this is a response blocking timeout, is the client and the server to establish a connection, waiting to receive data timeout, the real connection timeout I did not handle.
Solve:
Socket socket = NULL;
try {
Socket = new socket ();
SocketAddress socketaddress = new Inetsocketaddress (host, Port);
Socket.connect (socketaddress, 100);//Not even 0.1 millisecond disconnected
Socket.setsotimeout (timeout);/Response blocking timeout
This is good, IP not even on the 0.1-second disconnect, ConnectTimeout exception
Refer to this old brother's http://blog.csdn.net/tterminator/article/details/52494141 thanks ...