【发布时间】:2014-04-08 03:54:47
【问题描述】:
这是错误的完整堆栈跟踪
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2323)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2792)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:800)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
at mypackage.JChatComm.receiveMessage(JChatComm.java:83)
at mypackage.JThread.run(JThread.java:19)
at java.lang.Thread.run(Thread.java:701)
这是我的接收消息代码: 此函数创建对象 JPacket 的 ObjectInputStream 并打印该对象。 但是经过一次迭代,它会抛出 EOFException 并打印 4,11,8 和 stackTrace。
public boolean receiveMessage() throws IOException, ClassNotFoundException{
try{
System.out.println("4");
InputStream inFromServer = client.getInputStream();
System.out.println("11");
ObjectInputStream in = new ObjectInputStream(inFromServer);
//System.out.println("hellow owrol");
//System.out.println("5");
final JPacket jp;
jp = (JPacket) in.readObject();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("6");
if (type.equals("s")){
tab.ta.append("Client: "+jp.msg+"\n");
}
else {
cp.ta.append("Server: "+jp.msg+"\n");
}
}
});
System.out.println("other: "+jp.msg+ " Sent on:" + jp.a1);
//System.out.println("msg got");
return true;
}
catch (Exception ea){
System.out.println("8");
ea.printStackTrace();
return false;
}
}
这是我的 sendMessage 程序 该程序是发送消息的主程序。它始终可以正常工作并正确刷新输出流。但还是 receiveMessage 抛出错误。
public boolean sendMessage() throws IOException{
try{
System.out.println("3");
final String msg;
if (type.equals("c")){
msg = cp.tf.getText();
}
else msg = tab.tf.getText();
System.out.println(msg);
JPacket j1 = new JPacket(msg);
OutputStream outToServer = client.getOutputStream();
ObjectOutputStream out = new ObjectOutputStream(outToServer);
out.writeObject(j1);
System.out.println("13");
out.flush();
System.out.println("12");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (type.equals("s")){
tab.ta.append("You: "+msg+"\n");
tab.tf.setText("");
}
else {
System.out.println("Client");
cp.ta.append("You: "+msg+"\n");
cp.tf.setText("");
}
}
});
if(msg.equals("End Chat")) {
endChat();
return false;
}
else
return true;
}
catch (Exception ea){
ea.printStackTrace();
System.out.println("7");
return false;
}
}
我每次都在刷新对象输出流,但它仍然抛出相同的错误。
【问题讨论】:
-
client大概是套接字?如果它是同一个套接字,那么您写入它的内容将发送到您的服务器,而不是同一个套接字的输入流。 -
实际上这两种方法都是一个类的一部分,一次客户端套接字是由
new socket.connect(ip,port)实例化的客户端套接字,另一次在不同的运行中,它是通过接受服务器套接字的连接来实例化的。
标签: java sockets network-programming objectinputstream objectoutputstream