使用执行程序服务时java.net.ConnectException

时间:2014-07-03 00:23:55

标签: multithreading java-ee executorservice

我在下面收到此错误。如果我取出代码的执行程序服务部分,我的代码可以工作。因此,将其归结为大致几行代码。但我将包括必要的客户端和服务器代码

Error in connecting to server: 20999
java.net.ConnectException: Connection refused: connect
  at java.net.DualStackPlainSocketImpl.connect0(Native Method)
  at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
  at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
  at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
  at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
  at java.net.PlainSocketImpl.connect(Unknown Source)
  at java.net.SocksSocketImpl.connect(Unknown Source)
  at java.net.Socket.connect(Unknown Source)
  at java.net.Socket.connect(Unknown Source)
  at java.net.Socket.<init>(Unknown Source)
  at java.net.Socket.<init>(Unknown Source)
  at client.Client_Controller.connect(Client_Controller.java:32)
  at client.Client_Controller.<init>(Client_Controller.java:23)
  at client.Client_UI.<init>(Client_UI.java:29)
  at client.Client_UI$1.run(Client_UI.java:169)
  at java.awt.event.InvocationEvent.dispatch(Unknown Source)
  at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
  at java.awt.EventQueue.access$200(Unknown Source)
  at java.awt.EventQueue$3.run(Unknown Source)
  at java.awt.EventQueue$3.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
  at java.awt.EventQueue.dispatchEvent(Unknown Source)
  at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
  at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
  at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
  at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
  at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
  at java.awt.EventDispatchThread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
  at client.Client_Controller.outputStream(Client_Controller.java:45)
  at client.Client_Controller.<init>(Client_Controller.java:24)
  at client.Client_UI.<init>(Client_UI.java:29)
  at client.Client_UI$1.run(Client_UI.java:169)
  at java.awt.event.InvocationEvent.dispatch(Unknown Source)
  at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
  at java.awt.EventQueue.access$200(Unknown Source)
  at java.awt.EventQueue$3.run(Unknown Source)
  at java.awt.EventQueue$3.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
  at java.awt.EventQueue.dispatchEvent(Unknown Source)
  at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
  at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
  at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
  at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
  at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
  at java.awt.EventDispatchThread.run(Unknown Source)

以下是服务器代码:

public Server(int port, Client_Handler_Factory handlerFactory, ExecutorService executor) throws IOException {
    Objects.requireNonNull(port);
    Objects.requireNonNull(executor);

    this.serverSocket = new ServerSocket(port);
    this.handlerFactory = handlerFactory;
    this.executor = executor;
}

public void start() {

    executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                listen();
            }

            catch (IOException ex) {
                System.out.println("An exception occurred while the server was listening");
                ex.printStackTrace();
            }
        }
    });

}

public void listen() throws IOException {

    synchronized (this) {

        if (listening) {

            throw new IllegalStateException(
                    "The server has already started listening");
        }

        listening = true;

    }

    try {
        while (!closed) {

            socket = serverSocket.accept();

            executor.submit(new Runnable() {

                public void run() {

                    delegateToHandler(socket);

                }

            });
        }
    }

    catch (SocketException ex) {
        if (closed)
            System.out.println("Socket is closed!");
        else
            throw ex;
    }

}

private void delegateToHandler(Socket socket) {

    try {
        handlerFactory.createHandler(socket).handle();
    } catch (IOException ex) {
        System.out
                .println("Exception occured while handling the connection to "
                        + socket.getInetAddress());
    }

    finally {
        try {

            socket.close();

        } catch (IOException ex) {

            System.out.println("Exception occured while trying to close the connection to "
                            + socket.getInetAddress());

        }
    }
}

public void close() throws IOException {

    if (!closed) {
        closed = true;
        serverSocket.close();
        executor.shutdown();

    }
}

}

以下是服务器的主要方法:

  public static void main(String... args) throws Exception {
        ExecutorService executor = Executors.newCachedThreadPool();
        System.out.println("Server has started");
        try (Server server = new Server(20999, new ClientName_Handler.Factory(), executor))
        {

          server.start();

        }
      }
    }

以下是与服务器连接的客户端代码:

Client_Controller() {

    this.connect(hostName, port);
    this.outputStream();
    this.inputStream();

}

private void connect(String hostName, int port) {

    try {
        socket = new Socket(hostName, port);
    } catch (UnknownHostException ex) {
        System.out.println("Host was not found: " + hostName);
    } catch (IOException ex) {
        System.out.println("Error in connecting to server: " + port);
        ex.printStackTrace();
    }

}

private void outputStream() {

    try {
        out = new DataOutputStream(socket.getOutputStream());
        outObj = new ObjectOutputStream(socket.getOutputStream());
    } catch (IOException ex) {
        System.out.println("Output stream failure");
    }

}

private void inputStream() {

    try {
        in = new DataInputStream(socket.getInputStream());
        inObj = new ObjectInputStream(socket.getInputStream());
    } catch (IOException ex) {
        System.out.println("Input stream failure");
    }

}

public void closeConnection() throws IOException {

    try {
        this.sendMessage("Client_Close");
    }

    finally {

        try {
            out.close();
        }

        finally {
            try {
                in.close();
            }

            finally {
                socket.close();
            }
        }
    }
}

public void sendMessage(String message) throws IOException {

    try {
        out.writeUTF(message);
    }

    finally {
        out.flush();
    }

}

public String receiveMessage() {

    String input = null;

    try {
        input = in.readUTF();
    } catch (IOException ex) {
        System.out.println("Error receving the message from the server");
    }

    return input;

}

public Object receiveObject(String message) {

    Object input = null;

    try {
        sendMessage(message);
        input = inObj.readObject();     
        System.out.println(input);
    } catch (IOException | ClassNotFoundException ex) {
        System.out.println("Error receving the message from the server");
    }

    return input;

}

}

下面是代码行,如果我删除将允许客户端连接。这些代码行可以在方法start()和listen()下的服务器类中找到。非常感谢所有帮助。

    executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                listen();
            }

            catch (IOException ex) {
                System.out.println("An exception occurred while the server was listening");
                ex.printStackTrace();
            }
        }
    });


            executor.submit(new Runnable() {

                public void run() {

                    delegateToHandler(socket);

                }

            });

1 个答案:

答案 0 :(得分:0)

当您通过ExecutorService运行listen()方法时,它允许start()返回,这会导致您的try-with-resources块退出并关闭服务器套接字,因此您的客户端无需连接