问题
I'm using SocketChannel
to send message between a server and a client. Once a client connects with a server, the server opens the InputStreams
and OutputStream
in a try-with-resources try, to receive messages from the client and send messages to the client, like so:
try (ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {}
I want to access out
outside of the try. The try contains a while loop that repeatedly checks if messages has arrived on in
, which works fine.
I tried setting a global variable, say global_out
, by doing:
ObjectOutputStream global_out;
...
try (ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {
setOut(out);
while(should_check) {
Object message = in.readObject();
//do something
}
}
And then I tried writing to this OutputStream, like so:
public void sendMessage(Object message) {
global_out.writeObject(message);
}
I only call sendMessage(Object)
when should_ceck
is true
and test if global_out
is null
, which it isn't. However, sendMessage(Object)
never returns. If global_out
isn't null
, it must have been set to something, so why can't the resources be used before the try-with-resources
terminates?
Is there any way I can get around this?
来源:https://stackoverflow.com/questions/22663403/using-resources-of-try-with-resources-outside-try