Java---> Determine if IP and port can be connected

Source: Internet
Author: User

When we connect the device via IP and port, sometimes we need to give the user a response in a few seconds for the user experience, which requires some way to judge:

 Public voidConnect (String server,intServport)throwsioexception,unknownhostexception, sockettimeoutexception { inetaddress ad=inetaddress.getbyname (server); BooleanState = Ad.isreachable (+);//test whether the address can be reached, determine if IP can connect 1000 is the time-out        if(state) {System.out.println ("Connection succeeded" +ad.gethostaddress ()); } Else{System.out.println ("Connection Failed"); Throw NewIOException (); }        //1. Create a Socket instance: constructor establishes a TCP connection to the specified remote host and port//socket = new Socket (server, servport);Socket =NewSocket (); Socket.setreceivebuffersize (8192); Socket.setsotimeout (1000);//socket.setsotimeout (+);     socketaddressAddress =Newinetsocketaddress (server, servport); Try{ socket.connect (address, + );//1. Determine if IP, port can be connected}Catch(IOException e) {System.out.println ("New socket Server" + servport+ "Connection Failed"); Throw NewIOException (); } System.out.println ("Create a new socket"); //System.out.println ("Connected to server ... sending echo string"); //2. Communication via the socket's input and output stream: A socket Connection instance consists of a inputstream and a outputstream, and their usage is the same as other Java input and output streams. in =Socket.getinputstream (); out=Socket.getoutputstream (); Isalreadyconnected=1; //connect1 (server, servport);}

Through the above two methods, throw an exception, interrupt the connection, to meet the user experience

Java---> Determine if IP and port can be connected

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.