0

我正在尝试学习 Java 的网络编程,但我无法获得一个简单的聊天程序来连接服务器和主机。这是我正在经历的:

当我尝试将我的客户端程序连接到服务器时,我得到一个空指针异常并且它不会连接。

在调试时我发现了这条线

 connection.equals(server.accept());

在服务器类中的 waitForCommuinication() 方法中未执行。

这发生在线路

client = new Socket(InetAddress.getByName(chatServer), 50499);

在客户端类的方法 connectToServer() 中执行。

我只是使用我的本地主机 ip add 运行此代码

服务器类:

public class Server extends JFrame {

private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private int counter = 1;

public Server() {
    super ("Server");
    enterField = new JTextField();
    enterField.setEditable(true);
    enterField.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent event) {
            sendData(event.getActionCommand());
            enterField.setText("");

        }
    });

    add(enterField, BorderLayout.NORTH);
    displayArea = new JTextArea();
    add (new JScrollPane(displayArea));

    setSize(300,150);
    setVisible(true);
}



public void runServer() {
    try {
        server = new ServerSocket(50499, 100);
        //displayMessage("\n Listening on Port: " + server.getLocalPort() + "\n");

        while (true) {
            try {
                waitForCommunication();
                getStreams();
                processConnection();
            } catch (EOFException eofException) {
                displayMessage("\n Server terminated connection ");
            } finally {
                closeConnection();
                ++counter;
            }
        }
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
}

private void closeConnection() {
    displayMessage("\nTerminating connection\n");
    setTextFieldEditable(false);
    try {
        output.close();
        input.close();
        connection.close();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }

}

private void displayMessage(final String string) {
    SwingUtilities.invokeLater(new Runnable(){

        @Override
        public void run() {
            displayArea.append(string);
        }

    });

}

private void processConnection() throws IOException {
    String message = "Connection Sucessful";
    sendData(message);

    setTextFieldEditable(true);

    do {
        try {
            message = (String) input.readObject();
            displayMessage("\n" + message);
        } catch (ClassNotFoundException classNotFoundException) {
            displayMessage("\nnUnknown object type recieved");
        }
    } while (!message.equals("Client>>> TERMINATE"));
}

private void setTextFieldEditable(final boolean editable) {
    SwingUtilities.invokeLater(new Runnable(){

        @Override
        public void run() {
            enterField.setEditable(editable);

        }

    });

}

private void getStreams() throws IOException {
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();

    input = new ObjectInputStream(connection.getInputStream());

    displayMessage("\nGOt I/O stream \n");

}

private void waitForCommunication() throws IOException {
    displayMessage("Waiting for cennection \n");
    connection.equals(server.accept());
    displayMessage("Connection" + counter + " received from: "
            + connection.getInetAddress().getHostName());
}

private void sendData(String message) {
    try {
        output.writeObject("SERVER>>> " + message);
        output.flush();
        displayMessage("\nServer>>> " + message);
    } catch (IOException ioException){
        displayArea.append("\nError Writing Object");
    }
}
}

客户端类:

public class Client extends JFrame {

private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String chatServer; 
private Socket client; 

public Client(String host){
    super ("Host");

    chatServer = host;

    enterField = new JTextField();
    enterField.setEditable(false);
    enterField.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent event) {
            sendData(event.getActionCommand());
            enterField.setText("");
        }

    });

    add(enterField, BorderLayout.NORTH);

    displayArea = new JTextArea();
    add(new JScrollPane(displayArea));

    setSize(300,150);
    setVisible(true);
}

public void runClient(){
    try{
        connectToServer();
        getStreams();
        processConnection();
    } catch (EOFException eofException){
        displayMessage("\nClient terminated connection");
    } catch (IOException ioException){
        ioException.printStackTrace();
    } finally {
        closeConnection();
    }
}

private void closeConnection() {
    displayMessage("\nClosing connection");

    setTextFieldEditable(false);

    try{
        output.close();
        input.close();
        client.close();
    } catch (IOException ioException){
        ioException.printStackTrace();
    }

}

private void displayMessage(final String messageToDisplay) {
    SwingUtilities.invokeLater( new Runnable() {

        @Override
        public void run() {
            displayArea.append(messageToDisplay);

        }

    });

}

private void processConnection() throws IOException {
    setTextFieldEditable(true);

    do {
        try{
            message = (String) input.readObject();
        } catch (ClassNotFoundException classNotFoundException){
            displayMessage("\nUnknown object type recieved");
        }
    } while (!message.equals("SERVER>>> TERMINATE"));
}

private void setTextFieldEditable(final boolean b) {
    SwingUtilities.invokeLater(new Runnable(){

        @Override
        public void run() {
            enterField.setEditable(b);

        }
    });

}

private void getStreams() throws IOException {
     output = new ObjectOutputStream(client.getOutputStream());
     output.flush();

     input = new ObjectInputStream(client.getInputStream());

     displayMessage("\nGot I/O streams!\n");
}

private void connectToServer() throws IOException {
    displayMessage("Attempting connection\n");

    client = new Socket(InetAddress.getByName(chatServer), 50499);

    displayMessage("Connected to: " + client.getInetAddress().getHostName());
}

protected void sendData(String actionCommand) {
    try{
        output.writeObject("CLIENT>>> " + actionCommand);
        output.flush();
        displayMessage("\nCLIENT>>> " + actionCommand);
    } catch (IOException ioException){
        displayArea.append("\nError sending Message");
    }

}

}
4

1 回答 1

2

在 Server 类中,您有 NPE 连接的 waitForCommunication 方法为空。 connection.equals(server.accept());

我确定您需要类似 connection = server.accept();

于 2013-05-21T18:55:28.697 回答