I wan to write a message to a server. The first time I send a message everything works fine. But the second time I want to send another command the dos.writeUTF(message);
line is throwing the NullPointerException. I really don't know why.
GUICLIENT_INSTANCE
is for my Swing class
This is my initialize method:
private void initialize() {
if (name != null && ip != null && port != 0) {
String verify = "/v/" + name + "/" + ip + "/" + port + "/e/";
boolean connect = openConnection(ip, port);
if (connect) {
send(verify);
String receiveMsg = "";
String[] temp = {};
try {
try {
if (dis.available() > 0) {
receiveMsg = dis.readUTF();
}
} catch (Exception e2) {
e2.printStackTrace();
}
System.out.println(receiveMsg);
temp = splitMsg(receiveMsg, "/");
if (receiveMsg.startsWith("/er/")) {
if (temp[2].equals("disconnected")) {
s.close();
GUICLIENT_INSTANCE.connectFail();
}
} else {
System.out.println("Showing connected");
try {
System.out.println("Connected!");
GUICLIENT_INSTANCE.connected();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (Exception e1) {
GUICLIENT_INSTANCE.connectFail();
}
System.out.println(receiveMsg);
} else {
System.err.println("No server found with Address: " + ip + ":" + port);
GUICLIENT_INSTANCE.connectFail();
}
}
}
I open my connection with:
private boolean openConnection(String Sip, int port) {
try {
InetAddress ip = InetAddress.getByName(Sip);
s = new Socket(ip, port);
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
} catch (Exception e) {
return false;
}
return true;
}
This is the code of my send method:
public void send(String message) {
try {
if (s.isConnected()) {
dos.writeUTF(message);
} else {
System.err.println("Failed sending! No connection!");
}
} catch (Exception e) {
e.printStackTrace();
}
}