Java套接字连接问题

标签 java sockets

我正在尝试学习java网络编程,但在获取一个简单的聊天程序来连接服务器和主机之间时遇到了困难。以下是我的经历:

当我尝试将客户端程序连接到服务器时,出现空指针异常,并且无法连接。

调试时我发现了这一行

 connection.equals(server.accept());

服务器类中的waitForCommuinication()方法没有被执行。

当行

时发生这种情况
client = new Socket(InetAddress.getByName(chatServer), 50499);

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

我只是使用我的 localhost 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");
    }

}

}

最佳答案

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

我确信您需要类似的东西 connection = server.accept();

关于Java套接字连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16677059/

相关文章:

java - 与无参数 StackTraceElement 构造函数相关的 CXF IllegalAnnotationException

java - 使用 Olingo/ODATA 4 编写 ExpressionVisitor 的集成测试

Java(Netbeans): Connecting Google Search To JTextField

java - JPA @OneToOne 具有相同类型

python - 如何在 ssl python 套接字中设置密码

java - 文件传输服务器 <-> 客户端,文件不完整

java - 我应该关闭tcp连接吗?

java - 从生成的 pom 和源构建 Artifact

无法在Linux中使用Eclipse构建C项目

带有 beginReceive 的 c# 异步服务器