-1

i have a question about a project im working for school, im trying to send a packet via datagram packet but the send method i built keeps telling me null pointer exception, i checked the code and it should, in theory work, cant tell what i have done wrong(but then again im no expert),the port_to_send comes from the user entering the nickname of the person he wants to send a message to, then i ask the database that i have if it exists and if yes, returns the port that is associated with that nickname(when a user registers the password will be the port).Thank you in advance for your help. My Socket class:

public class socket extends Thread{

   InetAddress ip;

   int port;
   DatagramSocket sock;
   byte[] buf = new byte[1024];
   JTextArea jt = new JTextArea();

    public socket(JTextArea area){
       this.jt = area;
   }


   public void run(){
       try {
           InetAddress ip2 = InetAddress.getLocalHost();

           sock = new DatagramSocket(port, ip2);

           while(true){
               receivePacket();
           }

       } catch (Exception e) {
           JOptionPane.showMessageDialog(null, e);
           System.out.println("run of socket");
       }

   }

   public void sendPacket(String str, int pr) throws SocketException, IOException{
       try {
           System.out.println("in start of send packet");
           int len = str.length();
           byte[] b = new byte[len];
           str.getBytes(0, len, b, 0);
           InetAddress ip = InetAddress.getByName("localhost");
           DatagramPacket dp = new DatagramPacket(b, len, ip, pr);
           System.out.println(dp.getAddress()+ " " + dp.getPort());

           sock.send(dp);


       } catch (Exception e) {

           JOptionPane.showMessageDialog(null, e);
           System.out.println("catch of end packet");
       }

   }
   public void receivePacket(){


       try {
           System.out.println("in receive packet");
           DatagramPacket dp = new DatagramPacket(buf, port);
           sock.receive(dp);
           String str = new String(dp.getData(),0,0,dp.getLength());
           jt.append("\n"+ str);
           System.out.println(str);

       } catch (Exception e) {
           //Logger.getLogger(socket.class.getName()).log(Level.SEVERE, null, ex);
           JOptionPane.showMessageDialog(null, e);
           System.out.println("end of receivepacket ");
       }

   }

My chat class for the user to send, receive and read messages.

public class chat extends javax.swing.JFrame {

    /**
     * Creates new form chat
     */
    //private static socket s;

    private socket sock = new socket(msg_area);
    private String name2;

    static JTextArea area;




    public chat() { 
        initComponents();

    }
    public chat(String name){
        initComponents();
        this.name2 = name;
        jLabel2.setText(name2);
    }
    public void socket_start(){sock.start();}

 private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            // TODO add your handling code here:
            int port = 0;
            String msg = msg_text.getText();
            String nick2 = nick_to_send.getText();
            Class.forName("com.mysql.jdbc.Driver");
            java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sdp", "root", "");
            PreparedStatement st = conn.prepareStatement("Select * from client where NickName=?");
            st.setString(1,nick2);
            ResultSet rs = st.executeQuery();
            if(rs.next()){
                 port = rs.getInt("Port");
                System.out.println("testing1");
                sock.sendPacket(msg, port);
            }else{
                System.out.println("testing2");
            }//sock.sendPacket(msg, port);
            System.out.println(port);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
            System.out.println("chat of socket");
        }
    }  
 public static void main(String args[]) {

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                chat c = new chat("chat");
                c.setVisible(true);
                c.socket_start();
                c.setDefaultCloseOperation(EXIT_ON_CLOSE);

            }
        });


    }

In theory what should happen in my code is this, as a new user you register with a nickname and a password, it gets registered in my DB, then the chat opens up creates a new socket for you using your password as port, localhost as ip(i use localhost cause it only need to work in one machine, at least for now),if you want to send a message, you enter your friends nickname and it ask the DB if it exists returns port, uses that port to send the packet and he will receive it,where it shows up at his text area.

Since it is a null error does it mean the socket im trying to send the packet to does not exist?

Or is it that my send method is wrong somewhere?

Made a couple of changes,gonna leave the before code as reference New Socket class:

public class socket extends Thread{

   InetAddress ip;

//   String str = "";
   int port;
   DatagramSocket sock;
   byte[] buf = new byte[1024];
   JTextArea jt = new JTextArea();

    public socket(JTextArea area,int port){
       this.jt = area;
       this.port = port;
   }


   public void run(){
       try {
           //InetAddress ip2 = InetAddress.getLocalHost();

           //sock = new DatagramSocket(port, ip2);
           sock = new DatagramSocket(port);
           while(true){
               receivePacket();
           }

       } catch (Exception e) {
           JOptionPane.showMessageDialog(null, e);
           System.out.println("run of socket");
       }

   }

   public void sendPacket(String str, int pr) throws SocketException, IOException{
       try {
           System.out.println("in start of send packet");
           int len = str.length();
           byte[] b = new byte[len];
           str.getBytes(0, len, b, 0);
          // InetAddress ip = InetAddress.getByName("localhost");
          InetAddress ip = InetAddress.getLocalHost();
           DatagramPacket dp = new DatagramPacket(b, len, ip, pr);
//           InetAddress ip = InetAddress.getLocalHost();
//           DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, pr);
           System.out.println(dp.getAddress()+ " " + dp.getPort());

           sock.send(dp);


       } catch (Exception e) {
           Logger.getLogger(socket.class.getName()).log(Level.SEVERE, null, e);
//           JOptionPane.showMessageDialog(null, e);
//           System.out.println("catch of end packet");
       }

   }
   public void receivePacket(){


       try {
           System.out.println("in receive packet");
           DatagramPacket dp = new DatagramPacket(buf, port);
           sock.receive(dp);
           String str = new String(dp.getData(),0,0,dp.getLength());
           jt.append("\n"+ str);
           System.out.println(str);

       } catch (Exception e) {
           //Logger.getLogger(socket.class.getName()).log(Level.SEVERE, null, ex);
           JOptionPane.showMessageDialog(null, e);
           System.out.println("end of receivepacket ");
       }

   }

New Chat:

    int port_end;
    socket sock;
    private String name2;

    static JTextArea area;




    public chat() { 
        initComponents();

    }
    public chat(String name,int port){
        initComponents();
        sock = new socket(msg_area,port_end);
        sock.start();
        this.name2 = name;
        this.port_end = port;
        jLabel2.setText(name2);
    }
   private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            // TODO add your handling code here:
            int port = 0;
            String msg = msg_text.getText();
            String nick2 = nick_to_send.getText();
            Class.forName("com.mysql.jdbc.Driver");
            java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sdp", "root", "");
            PreparedStatement st = conn.prepareStatement("Select * from client where NickName=?");
            st.setString(1,nick2);
            ResultSet rs = st.executeQuery();
            if(rs.next()){
                 port = rs.getInt("Port");
                 port_end = port;
                System.out.println("testing1");
                sock.sendPacket(msg, port);
            }else{
                System.out.println("testing2");
            }//sock.sendPacket(msg, port);
            System.out.println(port);
        } catch (Exception e) {
//            JOptionPane.showMessageDialog(null, e);
//            System.out.println(e);
//            System.out.println("chat of socket");
            Logger.getLogger(socket.class.getName()).log(Level.SEVERE, null, e);
        }
    } 

Now what happens is a bit different, when i log in as a client i get the print on the receivepacket method(but only once which is strange, if its always listening,then i should get constant prints right?) and if i click send(sending as user2) i get

user2 8001(this is correct i have a print to confirm the user and port)

user2

in receive packet

testing1

in start of send packet

Name of my pc/my IP 8000(port of user1)

8000

these are the prints for the sending user, the receiving user only has one print

user1

user1 8000

in receive packet

but i get nothing else, if the send method is now correct then user1 should get a packet and append to text area. So my question now is if my code is now correct then how can i confirm that a packet is actually being sent, and, why am i not getting constant prints from receive method which is always listening.

Malsum
  • 91
  • 1
  • 5
  • 2
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – AndiCover Jan 28 '20 at 16:59
  • It helped, following the instructions on that link i got i understood the error starts at socket class ,send packet method, sock.send(dp), but the socket should exist,so i dont get why its happening.Also thanks for the help. – Malsum Jan 28 '20 at 17:19

1 Answers1

1
       InetAddress ip = InetAddress.getByName("localhost");
       DatagramPacket dp = new DatagramPacket(b, len, ip, pr);
       System.out.println(dp.getAddress()+ " " + dp.getPort());

       sock.send(dp);

Check whether ip actually contains an address structure. It may be null. I have worked with Datagram sockets before and got a similar error. My issue was that the address couldn't be resolved by the "getByName"-function.

I would have posted this as comment but I don't have enough rep

ilmu011
  • 80
  • 2
  • 8
  • that print gives me the following: localhost 127.x.x.x 8000 the 8000 is because im using my user2 to send a msg to user1 user1 has password/port 8000 since it does have info within it should work right?gonna try getLocalHost,maybe its better – Malsum Jan 28 '20 at 17:50