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(); } }
}
source share