Java多线程,套接字 [英] Java Multithreading,Sockets

查看:80
本文介绍了Java多线程,套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个可连续ping通LAN连接的线程.我想通过为每个IP创建新的Socket来做到这一点,同时在连接失败时处理异常.但是,创建套接字时序列超时的执行(我在代码中用注释对其进行了签名).

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).

我该如何解决此问题?

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

        }

    }
}

感谢您的时间

推荐答案

您正在尝试同时进行ip扫描程序(在所有192.168上循环)和端口扫描程序.因此,您可以搜索以下两种解决方案: 用于ping IP地址的Java代码 套接字:使用Java发现端口可用性

Your are trying to do both an ip scanner( loop on all 192.168) and a port scanner. So you could search solutions for both: java code to ping an IP address Sockets: Discover port availability using Java

对于多线程部分,它要测试的值为65536,它将生成过多的线程,因此您可以将ThreadPool与执行程序一起使用,如果花费太长的时间可以将其取消.

For the multithreading part, it makes 65536 value to test, it would make too many Threads, so you can use a ThreadPool with executors, and cancel it if it takes too long.

查看要使用的方法(我让您执行算法

see the method to use (i let you do the algorithm

tp = Executors.newWorkStealingPool(512); // to create up to 512 Threads
//todo the creation loop...
future = tp.submit(()->{/* your port scan */ return true;});
//todo the waiting processing
future.cancel(true);// to cancel your future

这篇关于Java多线程,套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆