Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a timeout when creating a new Socket

Tags:

java

I have a local network with DHCP and a few PCs. One of these should be my Server and get automatically connected to all others (clients). My idea was this: First, I create a server on every client (CServer) that is listening for a client programm from the server (SClient). When the SClient connects to a CServer, the SClient sends the CServer his IP, so he knows there will be the server on this IP. Then after trying all IPs in his IP range (e.g. 192.168.1.xxx), he starts the real server and all the clients connect to the known server IP. But when I try the following, the SClient just freezes at the first IP, when trying to connect to 192.168.1.0. How can i define a timeout or something similar that lets the SClient drop the unsuccessful connection and going on with 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();
    }
}

}

like image 287
Johannes Trümpelmann Avatar asked Mar 01 '12 23:03

Johannes Trümpelmann


1 Answers

I've found a solution for my problem. It was just initializing the Socket not with

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!

like image 164
Johannes Trümpelmann Avatar answered Oct 17 '22 13:10

Johannes Trümpelmann