1

i made a chat application using java sockets it all works fine in console but while making an interface for the client using JFrame form in netbeans i keep getting a null pointer exception in connectButtonActionPerformed method though i have initialized the socket that's gonna connect to the server socket ss; in :

public ChatMain() {
    initComponents();
        try {
    this.ss = new Socket(host, port);
        /* obtain an output stream to the server... */
            DataOutputStream outToServer = new DataOutputStream(this.ss.getOutputStream());
            /* ... and an input stream */
            BufferedReader infromserver = new BufferedReader(new InputStreamReader(this.ss.getInputStream()));
    } catch (IOException ex) {
            System.out.println(ex.getMessage());


    }
}

here is the whole client class :

public class ChatMain extends javax.swing.JFrame   {

private static BufferedReader inFromUser;
private static int port = 6789; /* port to connect to */
private static String host = "localhost"; /* host to connect to */
public  static  Socket ss;             
public static String username;

 BufferedReader infromserver;
DataOutputStream outToServer;
Boolean isConnected = false;


public ChatMain() {

    initComponents();
        try {
    this.ss = new Socket(host, port);
        /* obtain an output stream to the server... */
            DataOutputStream outToServer = new DataOutputStream(this.ss.getOutputStream());
            /* ... and an input stream */
            BufferedReader infromserver = new BufferedReader(new InputStreamReader(this.ss.getInputStream()));
    } catch (IOException ex) {
            System.out.println(ex.getMessage());


    }
}

private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
    // TODO add your handling code here:
    if (isConnected == false) {
        username = usernameField.getText();  
        usernameField.setEditable(false);


        try {

            outToServer.writeBytes(username + '\n');
            String serverResponse = infromserver.readLine();
            chatTextArea.append(serverResponse + '\n');
            if (serverResponse.equalsIgnoreCase("SERVER: OK")) {
                isConnected = true; // Used to see if the client is connected.

            }

        } catch (Exception ex) {
            chatTextArea.append("Cannot Connect! Try Again. \n");
             System.out.println(ex.getMessage());


            usernameField.setEditable(true);
        }
    } else if (isConnected == true) {
        chatTextArea.append("You are already connected. \n");
    }

}                                             


/**
 * @param args the command line arguments
 */
public static void main(String args[]) throws IOException {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new ChatMain().setVisible(true);
        }

    });
}



// Variables declaration - do not modify                     
private javax.swing.JTextArea chatTextArea;
public static javax.swing.JButton connectButton;
private javax.swing.JButton disconnectButton;
private javax.swing.JTextArea inputTextArea;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
public static javax.swing.JTextArea onlineUsersArea;
private javax.swing.JButton sendButton;
private javax.swing.JButton update;
public static javax.swing.JTextField usernameField;
// End of variables declaration                   

}

i know if i initialized the server socket inside connectButtonActionPerformed method it will work fine **but then i have to reinitialize it in every action method and as far as i know i should use only one socket connected to the server for each client ** .. the StackTrace

    java.lang.NullPointerException
at my_private_chatting.ChatMain.connectButtonActionPerformed(ChatMain.java:194)
at my_private_chatting.ChatMain.access$000(ChatMain.java:23)
at my_private_chatting.ChatMain$1.actionPerformed(ChatMain.java:89)

this line throws the exception outToServer.writeBytes(username + '\n');in the connectButtonActionPerformed method... thanks in advance

  • @Hovercraft Full Of Eels it's quite obvious if you have read the code or the question carefully u'll notice that the null pointer exception is because of the server socket not being initialized – rama haj ali Jun 22 '17 at 03:00
  • Why would a client class even use a server socket? That class is usually only used by servers. – Hovercraft Full Of Eels Jun 22 '17 at 03:02
  • In fact the code above doesn't even have a variable of ServerSocket type -- I think that you're confusing terms here. – Hovercraft Full Of Eels Jun 22 '17 at 03:02
  • Your problem is still a NPE and it's likely due to your shadowing your stream-using variables. Look up variable shadowing and you'll see what you're doing wrong. And yes, I've read the code and the question, and it's just like a thousand other NPE questions -- if you study which variable is null, you can look back to see why its null and discover your variable shadowing. I suggest that you do this. – Hovercraft Full Of Eels Jun 22 '17 at 03:03
  • Edit: it's ***definitely*** due to your shadowing the in and out from stream variables -- **don't re-declare them**. – Hovercraft Full Of Eels Jun 22 '17 at 03:06
  • i'm using Socket not ServerSocket ... ` public static Socket server; ` – rama haj ali Jun 22 '17 at 03:06
  • Then don't call it a "server socket", not unless you're trying to confuse folks since server socket has an entirely different connotation. But more importantly, in the future when asking about exceptions, search on the exception first, always show the stacktrace, and always indicate which line throws the exception, and in this case **which variable is null**. – Hovercraft Full Of Eels Jun 22 '17 at 03:08
  • @HovercraftFullOfEels i've edited it .. i hope it's clear now .. thank you – rama haj ali Jun 22 '17 at 03:37
  • The line indication just confirms what I've said above -- you're shadowing the `outToServer` variable, as well as other variables by re-declaring them unnecessarily. Again, the solution is not to do this. Please check the 2nd duplicate question used to close yours. – Hovercraft Full Of Eels Jun 22 '17 at 16:30
  • @HovercraftFullOfEels it worked thank you so much ^_^ – rama haj ali Jun 22 '17 at 22:07

0 Answers0