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