Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

Java Multithreading,Sockets

I am trying to implement a Thread which pings LAN connections continously. I would like to do that by creating new Socket for each IP, while handling exceptions if it fails to connect. However, the execution of the sequence time outs at creating the socket (i signed it with a comment in the code).

How could i solve this Problem?

class Ping implements Runnable
{

    private int actPort = 1024; 

    public void run()
    {           
        Socket s;
        int[] ip = {192,168,0,0};

        while(true){

            try {

                for(int i = 0;i<256;i++)
                {
                    ip[2] = i;

                    for(int j = 0;j<256;j++)
                    {

                        ip[3] = j;
                        String address = ip[0]+"."+ip[1]+"."+ip[2]+"."+ip[3];
                        s = new Socket(address,actPort); // EXECUTION STOPS
                        System.out.println(address);                            
                    }
                }                   

            } catch (Exception e)
            {
                e.printStackTrace();
            }

        }

    }
}

Thanks for your time

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are creating Socket, which is a TCP/IP Stream and creates statefull connection between you (client) and given IP, PORT. I assume, this program stop while creating first Socket.

If you look at the API of Socket class:

 * If UDP socket is used, TCP/IP related socket options will not apply.
 *
 * @param      host     the IP address.
 * @param      port      the port number.
 * @param      stream    if {@code true}, create a stream socket;
 *                       otherwise, create a datagram socket.
@Deprecated
public Socket(InetAddress host, int port, boolean stream) throws IOException {
    this(host != null ? new InetSocketAddress(host, port) : null,
         new InetSocketAddress(0), stream);
}

This is @Deprecated version of creating UDP Socket, but what you REALLY need is DatagramPacket from java.net, which creates stateless connection, and may be timed out if packet didn't come to the end.

Look here for some example code of writing DatagramPacket:

https://github.com/awadalaa/Socket-Programming-Java/blob/master/UDP-Pinger/PingClient.java


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...