I have implemented a server client chat program using GUI. When the server is run, the client tries to connect to the server. When connection established, each one sends a message first, then chat, i.e, in my case, the client send the server a msg "client" and then the server sends a msg "server". Then they can chat. Problem is the server receives the msg "client" and the client does not receive the msg "server". At client console, nullpointerexception is occurred. And after that, only the server can send messages to the client and it is displayed at client side. The codes are shown below and an image is attached for the GUI. Both client and server have same interface. Note that codes for GUI components are not shown for simplicity. The method private void msg_sendActionPerformed is for the SEND button - see the GUI image. see GUI image error: Exception in thread "main" java.lang.NullPointerException at chatapp.client.main >> chatmate.setText(sss);
import java.io.*;
import java.net.*;
public class server extends javax.swing.JFrame {
static ServerSocket ss;
static Socket s=null;
static PrintStream p;
static BufferedReader b;
private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {
String m;
m=msg_text.getText();
p.println(m);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new server().setVisible(true);
}
});
String msgin;
ss = new ServerSocket(444);
s=ss.accept();
p = new PrintStream(s.getOutputStream());
b = new BufferedReader(new InputStreamReader(s.getInputStream()));
String sss = b.readLine();
chatmate.setText(sss);
p.println("server");
while (!(msgin=b.readLine()).equals("exit"))
{
msg_area.setText(msg_area.getText()+"\n"+msgin);
}
}
}
package chatapp;
import java.net.*;
import java.io.*;
public class client extends javax.swing.JFrame {
static Socket s;
static PrintStream p;
static BufferedReader b;
private void msg_sendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String m;
m=msg_text.getText();
p.println(m);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new client().setVisible(true);
}
});
s = new Socket("localhost",444);
p = new PrintStream(s.getOutputStream());
b = new BufferedReader(new InputStreamReader(s.getInputStream()));
p.println("client");
String sss= b.readLine();
chatmate.setText(sss);
String msgin;
while (!(msgin=b.readLine()).equals("exit")) // waits until gets msg
{
msg_area.setText(msg_area.getText()+"\n"+msgin);
}
}
}