Java聊天程序:由于空指针异常,客户端类无法正常工作

时间:2016-04-20 17:09:59

标签: java nullpointerexception

客户端类:

public void connect(String user){
            try{
                host = socket.getInetAddress();
                socket = new Socket(host,port);

            }

        }

登录类:

login.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {

                String user = textInput.getText();
                Client client = new Client(username, 7777);
                client.setVisible(true);
                try{
                  client.connect(username);
                }
                catch(NullPointerException e){
                  e.printStackTrace();
                }
        }

    });

我正在调用Client类的连接,我尝试捕获NullPointerException但我仍然收到错误。我还尝试插入null check代替try and catch clause 我试着环顾四周,但我没有找到任何答案。有人能告诉我什么错了吗?我想要的是客户端成功连接。

3 个答案:

答案 0 :(得分:0)

在调用connectClient()之前,您能否确保启动clientSocket。

答案 1 :(得分:0)

最初,似乎有一个局部变量声明。评论表明这可能是错误的。因此问题是Client类实例化了一个对象,但Login类没有获得对它的引用。

EDIT2 :经过额外讨论后,看来尽管有main方法,但实际的启动类是Login类,而不是Client类类。因此,client对象未实例化。

将实例化移动到Login类解决了NPE。

public class Login {
  //declare and instantiate a Client object
  static Client client = new Client();
 ....

  loginB.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent e) {

            String username = usernameTF.getText();
            ClientGUI clientgui = new ClientGUI(username, 7777);
            clientgui.setVisible(true);
            try{
              // get the instantiated client
              System.out.println("Attempting connection for " + username +  
                "(client == null): " + (client == null ? "true" : "false"));

              // use the static variable
              client.connectClient(username);
            }
            catch(NullPointerException npe){
              npe.printStackTrace();
            }
    }

});
}

答案 2 :(得分:0)

您必须更改您的connectClient方法

public void connectClient(String user){
        try{
            //clientSocket is not instantiated yet
            host = InetAddress.getByName("127.0.0.1");
            clientSocket = new Socket(host,port);
            String connected = user+" just connected";
            clientGUI.appendMessage(accepted+"\n"+connected);
            serverGUI.appendEventsLog(accepted+"\n"+connected);

        new ClientHandler().run();

        }
        catch(Exception e){
            sendMessage("Connection error: "+e);
            serverGUI.appendEventsLog("Client "+new ClientGUI(username, port)+" failed to connect");
        }

    }