我有发送工作,但服务器端不会收到数据输入流中发送的对象。该类是序列化的,并在发送时工作,但我不确定为什么它没有被服务器接收。
这是我的代码:
Server.ois = new ObjectInputStream(client.getInputStream());
while(Server.ois.available() != 0) {
try {
TriangleSend ts = (TriangleSend)Server.ois.readObject();
send(ts);
Server.ois.close();
} catch (Exception e) {
continue;
}
}
这一切都在while
循环和try
中。它还会在收到时生成异常。
send(TriangleSend
)方法是:
public static void send(TriangleSend coords) {
for (Socket client : Server.clients) {
try {
if (client != null) {
try {
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
oos.writeObject(coords);
oos.flush();
} catch (Exception e) {}
}
} catch (NullPointerException e) {
continue;
}
}
}
编辑: 源代码和例外:http://pastebin.com/rYzqduer
这是一个例外:
java.io.StreamCorruptedException: invalid stream header: 73720027
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at com.gopro2027.lwjgl.server.ServerThread$1$1.run(ServerThread.java:88)
at java.lang.Thread.run(Thread.java:745)
Could not send data Timeout: 0
答案 0 :(得分:0)
Tyler - 在构造ObjectOutputStream之前用BufferedOutputStream包装客户端的输出流 - 相反,在构造服务器端的ObjectInputStream之前执行BufferedInputStream。这应该有助于读/写过程。
服务器端:
Server.ois = new ObjectInputStream(new BufferedInputStream(client.getInputStream()));
while(Server.ois.available() != 0) {
try {
TriangleSend ts = (TriangleSend)Server.ois.readObject();
send(ts);
Server.ois.close();
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
发送三角形:
public static void send(TriangleSend coords) {
for (Socket client : Server.clients) {
if (client != null) {
try {
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(client.getOutputStream()));
oos.writeObject(coords);
oos.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
删除了修改
答案 1 :(得分:0)
while(Server.ois.available() != 0) {
available()
不是流结束的有效测试。见Javadoc。您应该将循环更改为while (true)
,并在捕获EOFException
时中断。