0

クライアントとサーバーの間でオブジェクトをバウンスできません。

オブジェクトを作成します。一部のフィールドを更新します。サーバーに送信します。(この部分は機能します)

SomeObject thisObject = new SomeObject();
thisObject.setSomeValue(13);          // update object to be sent

PrintStream toServer = new PrintStream(sock.getOutputStream());

ObjectOutputStream oos = new ObjectOutputStream(toServer);

oos.writeObject(thisObject);
oos.close();

toServer.println(oos);               // send object to server
toServer.flush();

この直後、サーバーはさらにいくつかの値を更新し、1919 に設定します。

ObjectInputStream objFromClient = new ObjectInputStream(new BufferedInputStream(
        sock.getInputStream()));

Served thisObject = (Served) objFromClient.readObject();
thisObject.setSomeValue(1919);

次に、サーバーはオブジェクトをクライアントに送り返します

toClient = new PrintStream(sock.getOutputStream());
ObjectOutputStream oos = new ObjectOutputStream(toClient);

oos.writeObject(thisObject);

oos.close();
objFromClient.close();
sock.close();

しかし、クライアント側でオブジェクトを取得するときが来ると..プログラムはSocket Closed例外で失敗します

ObjectInputStream objFromServer = new ObjectInputStream(
    new BufferedInputStream(sock.getInputStream()));      //java.net.SocketException: Socket is closed

thisObject = (Served) objFromServer.readObject();
....

問題を理解するのを手伝ってください

4

1 に答える 1

2

私の推測ではSocket、クライアントからの送信と受信の両方に同じものを使用していると思います。ObjectOutputStreamクライアントで を閉じると、基にOutputStreamなる が閉じられ、それが を閉じますsock。次に、以下で再利用しようとすると、閉じられており、例外がスローされます。

代わりに、トランザクションが完了するのを待ってから、クライアント コードでリソースを閉じます (finallyちなみに、これはブロックで行う必要があります)。または、待機に問題がある場合は、Socket代わりに new を使用してください。

于 2012-04-08T02:43:44.480 に答える