我正在制作一对客户端-服务器。我的客户端很好地连接到服务器,它通过套接字创建ObjectInputStream(socket.getInputStream()),从服务器到客户端,反之亦然。然后,出于某种神秘的原因,我的服务器的ObjectInputStream不知何故捕获了一个空对象。客户端没有通过套接字发送任何东西(我确实在对象发送方法上放置了/../来确保这一点,甚至System.out.print打印了之前发送的所有对象)服务器只捕获了一次神秘对象,之后客户端发送的所有对象都正常工作。。
class ClientThread extends Thread {
//The socket where to listen/talk
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
InputStream fInput;
OutputStream Output;
//my unique id (easier for deconnection)
int id;
//Objects that we will be receiving
Incomingdata datain;
//the date we connect
String date;
Player player;
boolean Connected = false;
//Constructor
ClientThread(Socket socket){
id = uniqueId++;
this.socket = socket;
try{
sOutput = new ObjectOutputStream(socket.getOutputStream());
sInput = new ObjectInputStream(socket.getInputStream());
Output = socket.getOutputStream();
} catch (Exception e){
System.out.println("Couldn't create Input/Output streams");
}
date = new Date().toString();
}
// what will run forever
public void run() {
// to loop until LOGOUT
Connected = true;
while(Connected) {
try {
datain = (Incomingdata) sInput.readObject(); //<--- this catches the mystical null! Even if nothing is sent over the socket?
}
catch (IOException e) {
TextArea.AddLine("Exception reading Streams: " + e);
break;
}
catch(ClassNotFoundException e2) {
break;
}
只有发送null,才能接收null。
(人们普遍误解readObject()
在流的末尾返回null。事实并非如此。)