Socket Connection Timeout handling Java

Source: Internet
Author: User

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 ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.