我见过一些人问过类似的问题,但任何人发布的唯一答案是你不应该这样做。
但我已经对它进行了两种方式的测试 - 它只能以这种方式工作。
服务器端
try {
// Obtain input and output streams to the client
while(true) {
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Object input = in.readObject();
if(input == RequestEnums.GETCURRENTGRID) {
out.writeObject(ContagionServerData.getImagePixels());
out.writeObject(ContagionServerData.getImageHeight());
out.writeObject(ContagionServerData.getImageWidth());
}
}
} catch( Exception e ) {
e.printStackTrace();
}
客户端
try {
inputStream = new ObjectInputStream(serverSocket.getInputStream());
outputStream = new ObjectOutputStream(serverSocket.getOutputStream());
outputStream.writeObject(RequestEnums.GETCURRENTGRID);
int[] imagePixels = (int[]) inputStream.readObject();
int imageHeight = (Integer) inputStream.readObject();
int imageWidth = (Integer) inputStream.readObject();
copyImage(background, imagePixels, imageHeight, imageWidth);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
这整天有效。
但如果我把它改成这个——
try {
// Obtain input and output streams to the client
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
while(true) {
Object input = in.readObject();
if(input == RequestEnums.GETCURRENTGRID) {
out.writeObject(ContagionServerData.getImagePixels());
out.writeObject(ContagionServerData.getImageHeight());
out.writeObject(ContagionServerData.getImageWidth());
out.flush();
}
}
} catch( Exception e ) {
e.printStackTrace();
}
(我在代码的更远处创建了输入和输出流)
try {
outputStream.writeObject(RequestEnums.GETCURRENTGRID);
outputStream.flush();
int[] imagePixels = (int[]) inputStream.readObject();
int imageHeight = (Integer) inputStream.readObject();
int imageWidth = (Integer) inputStream.readObject();
copyImage(background, imagePixels, imageHeight, imageWidth);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
然后我第一次从服务器成功接收到正确的数据 - 但此后每次 - 我只收到相同的数据而不是更新的数据,并且没有错误说明原因。