Add timeout when creating a new socket

I have a local area network with DHCP and several PCs. One of them should be my Server and automatically connect to all the rest (clients). My idea is this: First, I create a server on each client (CServer), which listens to the client program from the server (SClient). When SClient connects to CServer, SClient sends CServer its IP address, so it knows that there will be a server on that IP server. Then, trying all the IP addresses in its IP range (for example, 192.168.1.xxx), it starts a real server, and all clients connect to the known IP address of the server. But when I try to do the following, SClient just hangs at the first IP when trying to connect to 192.168.1.0. How can I determine a timeout or something similar that allows SClient to refuse a failed connection and go to 192.168.1.1?

import java.lang.*; import java.io.*; import java.net.*; class SClient { public SClient() { for(int i = 120; i < 125; i++){ try{ InetAddress addr = InetAddress.getLocalHost(); String addrs = addr+""; String ip = addrs.substring(addrs.indexOf("/")+1); Socket s1 = new Socket("192.168.1." + i, 1254); OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); dos.writeUTF(ip); dos.close(); s1out.close(); s1.close(); }catch(IOException e){} } } } 

and

 import java.lang.*; import java.io.*; import java.net.*; class CServer { public CServer() throws IOException{ ServerSocket s = new ServerSocket(1254); while(true){ Socket s1=s.accept(); InputStream s1In = s1.getInputStream(); DataInputStream dis = new DataInputStream(s1In); String st = new String (dis.readUTF()); System.out.println(st); dis.close(); s1In.close(); s1.close(); } } 

}

+2
source share
2 answers

I found a solution for my problem. It was just Socket initialization, not

 Socket s1 = new Socket("192.168.1." + i, 1254); 

but with

 Socket s1 = new Socket(); s1.setSoTimeout(200); s1.connect(new InetSocketAddress("192.168.1." + i, 1254), 200); 

Thanks anyway!

+16
source

This is much easier to do with UDP. General logic:

  • Define a known port for 'discovery'
  • Any start-up computer sends the message "Master Request Server"
  • If the response is not received in this message during the period of time you determine, then the machine that sent it automatically designates it as a server.
  • From now on, any machine that sends a "Master Request Server" message will receive a response from the master with its IP address and "communication port"
  • Connect a new computer to the server on the communication port and start sending messages.

You may encounter situations where more than one server believes that this is the master in this scenario, and then you need a conflict resolution process, but the diagram should give you a general idea of ​​the process that will work for you.

+1
source

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


All Articles