1

実行中のサービスについてローカルネットワークをスキャンするクラスを作成しようとしています。

問題は、アドレスがアクティブでない(応答がない)場合、5秒以上ハングアップすることです。これは適切ではありません。

このスキャンを数秒で完了させたいです。誰かアドバイスはありますか?

私のコード部分は以下の通りです

        int port = 1338;
    PrintWriter out = null;
    BufferedReader in = null;

    for (int i = 1; i < 254; i++){

        try {
            System.out.println(iIPv4+i);
            Socket kkSocket = null;

            kkSocket = new Socket(iIPv4+i, port);

            kkSocket.setKeepAlive(false);
            kkSocket.setSoTimeout(5);
            kkSocket.setTcpNoDelay(false);  

            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
            out.println("Scanning!");
            String fromServer;
            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Server here!"))
                    break;
            }

        } catch (UnknownHostException e) {

        } catch (IOException e) {

        }
    }

答えてくれてありがとう!これがこれを探している他の人のための私のコードです!

        for (int i = 1; i < 254; i++){

        try {
            System.out.println(iIPv4+i);
            Socket mySocket = new Socket();
            SocketAddress address = new InetSocketAddress(iIPv4+i, port);

            mySocket.connect(address, 5);   

            out = new PrintWriter(mySocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            out.println("Scanning!");
            String fromServer;
            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Server here!"))
                    break;
            }

        } catch (UnknownHostException e) {

        } catch (IOException e) {

        }
    }
4

2 に答える 2

4

を呼び出して、サーバーに明示的に接続してみることができますSocket.connect( address, timeout )

 Socket kkSocket = new Socket();
 kkSocket.bind( null )/ // bind socket to random local address, but you might not need to do this
 kkSocket.connect( new InetSocketAddress(iIPv4+i, port), 500 ); //timeout is in milliseconds
于 2011-02-10T15:01:10.963 に答える
3

noargコンストラクターを使用して未接続のソケットを作成し、小さなタイムアウト値でSocket()呼び出すことができます。connect(SocketAddress endpoint, int timeout)

Socket socket = new Socket();
InetSocketAddress endpoint = new InetSocketAddress("localhost", 80);
int timeout = 1;
socket.connect(endpoint, timeout);
于 2011-02-10T15:05:45.113 に答える