问题描述
我想向服务器写一条消息。我第一次发送消息时一切正常。但是第二次我想发送另一个命令时,dos.writeUTF(message);
行抛出了 NullPointerException。我真的不知道为什么。
GUICLIENT_INSTANCE
用于我的 Swing 课程
这是我的初始化方法:
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();
}
}
}
我打开我的连接:
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;
}
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();
}
}
解决方法
试试
public void send(String message) {
if (message == null) {
throw new IllegalArgumentException("null message not allowed");
}
if (dos == null) {
throw new IllegalStateException("output stream is null");
// or new IOException
}
...