服务器多客户端

时间:2015-04-15 15:14:45

标签: java

如果有可能性,我需要有人解释另外两个错误! 我想将一个对象发送给多个客户(客户端),但执行它时会出现错误! 第一个是:线程“Thread-2”中的异常java.lang.NullPointerException     在ClientServer.Master $ Worker.send(Master.java:177)

第二个是:java.net.ConnectException:连接被拒绝:连接     at java.net.PlainSocketImpl.socketConnect(Native Method)

     public void run() {
        for (int k = 0; k < MAX_IT; k++) {            
            ServerData C = new ServerData(getSousPop(ID), problem);
            try {
                send(C);// here is the first
                Object receiveRequest = receive();
                System.out.println("Recept");
                if(receiveRequest instanceof ClientData){
                    Population pop = ((ClientData)receiveRequest).getPop();
                    LocalePop = pop.clone();
                    SetReady(ID, true);....

这是工人建构者

     public Worker(int ID) {
        this.ID = ID;
        try {
            soc = new Socket(IP[ID], ports[ID]);// and the second is here
            in = new ObjectInputStream(soc.getInputStream());
            out  = new ObjectOutputStream(soc.getOutputStream());
        } catch (UnknownHostException ex) {
            Logger.getLogger(Master.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Master.class.getName()).log(Level.SEVERE, null, ex);
        } 
        start();
    }

1 个答案:

答案 0 :(得分:0)

您在同一个实例中调用start方法两次,第二次抛出IllegalThreadStateException

  1. lunch方法中的一个
  2. 构造函数内的其他start调用

  3. for(int i = 0; i < IP.length; i++) {
        workers[i] = new Worker(i);
    }
    

    这将调用Worker构造函数,它也会启动线程:

     public Worker(int ID) {
        this.ID = ID;
        [...]
        start();
    }
    

    for(int i = 0; i < IP.length; i++) {
        workers[i].start();
    }
    

    将重新遍历线程,然后再次启动它们(使用IllegalThreadStateException失败)。

    删除构造函数中的start调用或for周期。