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.