Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...