Java套接字连接问题

时间:2013-05-21 18:32:43

标签: 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");
    }

}

}

1 个答案:

答案 0 :(得分:2)

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

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