Terminating socket lock in java

I have Java juice calling the server. However, I do not know at what address I can get to the server, so I put several sockets in several threads, and they try to reach the server each at the same address. My question is that I do not want to wait for a timeout, but I do not know how to properly stop sockets and their flows.

the code:

socket = new Socket();
socket.connect(endpoint, timeout); // **Blocking method**
OutputStream out = socket.getOutputStream();
//Write Data here

How can I abort an operation? I believe that the Thread.stop()bad style, and it also does not work properly. .NET Tcp endpoints have a non-blocking method pendingthat allows the use of uinsg boolean flags, but I could not find something similar

+4
source share
1 answer

I do not know at what address I can get to the server, so I have several sockets in several threads, and they try to reach the server each at the same address.

Bad. BAD solution. Follow the logical step to determine the server address. Or do something to help you find out about the IP address of the server.

Only do so if it is your last hope.

My problem is that I do not want to wait for a timeout, but have no idea how to stop sockets and their flows properly.

You have no other timeout option. Socket.connect () blocks. You cannot do anything but wait.

, . , . ( ).

? Thread.stop() , .

, Thread.stop() Thread.interrupt(). .

, close() .

- . - . - 10 .

,

- , a java.net.SocketTimeoutException, Socket . - > 0. - -.

, try-catch-finally . .

, , :

try{
   socket = new Socket();
   socket.connect(endpoint,timeout); // **Blocking method**
   OutputStream out = socket.getOutputStream();
   //Write Data here
}
catch(Exception e){
   e.printStackTrace();
}
finally{
   socket.close();
}
0

Source: https://habr.com/ru/post/1653532/


All Articles