Using resources of try-with-resources outside try - java

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?

Related

I'm misunderstanding something on how to set up sockets, but I'm not suer if it's client side, server side, or both

I'm setting up a simple program to test starting a server, and I'm getting a silent failure state. My client seems to think it has sent, while my server doesn't think it's recieving. The two are managing the initial connection, it's just sending things after that where it's failing.
I've cut things down to the core of where it's currently failing I think.
Here's part of the Client code
public void Client (int port, String ip)
{
try {
sock = new Socket(ip, port);
System.out.println("Found the server.");
streamInput = new DataInputStream(sock.getInputStream());
// sends output to the socket
streamOutput = new DataOutputStream(
sock.getOutputStream());
streamOutput.writeChars("Client Begining Conversation");
System.out.println(streamInput.readUTF());
}
catch (UnknownHostException u) {
System.out.println(u);
return;
}
catch (IOException i) {
System.out.println(i);
return;
}
}
public static void main(String[] args) throws IOException {
// create the frame
try {
ClientGui main = new ClientGui();
main.Client(8000,"127.0.0.1");
main.show(true);
} catch (Exception e) {e.printStackTrace();}
Here's server code.
public Server(int port) throws Exception
{
ServerSocket gameServer = new ServerSocket(port);
Socket gameSocket = gameServer.accept();
System.out.println("Client has connected");
// to send data to the client
PrintStream dataOutput
= new PrintStream(gameSocket.getOutputStream());
// to read data coming from the client
BufferedReader reader = new BufferedReader( new InputStreamReader(
gameSocket.getInputStream()
));
//play logic
Play(reader,dataOutput);
public void Play(BufferedReader reader, PrintStream dataOutput) throws Exception
{
String received, textSent;
System.out.println("Waiting for response.");
received = reader.readLine();
System.out.println("Client has responded");
//contenue until 'Exit' is sent
while (received != "Exit" || received != "exit") {
System.out.println(received);
textSent = received + "recieved";
// send to client
dataOutput.println(textSent);
}
}
My client gets to here -
Found the server.
and my server gets to here -
Trying to start server.
Client has connected
Waiting for response.
At which point, it just hangs forever, each side waiting for the other. It doesn't throw an error, it just... waits until I force it closed.
So it appears that I'm either doing something wrong when I send with "streamOutput.writeChars" in my client, or I'm doing something wrong when I receive with my server with "reader.readLine();", but I can't figure out what.
Or I could be doing something more fundamentally wrong.
The problem is that reader.readLine() doesn’t return until it sees a new line character, but streamOutput.writeChars("Client Begining Conversation") doesn’t send one.
More generally, mixing a DataOutputStream on the client with a BufferedReader on the server won’t work reliably, as the latter expects plain text, while the former produces formatted binary data. For example, the character encoding might not match. The same applies to communication in the opposite direction with PrintStream and DataInputStream. It’s best to pick either a text based or binary protocol and then be consistent about the pair of classes used on both the client and server.
In the case of a text protocol, an explicit character encoding should be defined, as the default can vary between platforms. As a learning exercise, it might not matter, but it’s a good practice to be explicit about specifying a character encoding whenever handling networked communication. UTF-8 is a good choice unless there’s a specific reason to use another one.
In addition, it is generally preferred to use PrintWriter instead of PrintStream for text output in new code. Read this answer for an explanation.

socket closing early on multiple transfers

I'm trying to send an object over the network to another computer (or the same computer) and then have said computer send an object back.
On the sending computer, I send the object and receive the returned object:
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject(object);
Object returnedObject;
socket.setSoTimeout(timeout);
try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
returnedObject = (Object) ois.readObject();
}
return returnedObject;
On the receiving computer, I receive the object:
Object object;
socket.setSoTimeout(timeout);
try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
object = (Object) ois.readObject();
}
return object;
and then send an object back:
socket.setSoTimeout(timeout);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject(object);
The error I get back is:
SEVERE: null java.net.SocketException: Socket is closed at
java.net.Socket.setSoTimeout(Socket.java:1137) at
and it occurs while attempting to send an object back on the receiving computer.
The socket on the sending computer is using the same address and port as the socket on the receiving computer.
This exception means that you closed the socket and then continued to use it. Specifically, you closed the ObjectInputStream at the end of the try-with-resources block where it is declared. That closes the other stream of the socket and the socket itself.
Don't use new object streams per transfer. Use the same ones for the life of the socket, at both ends.
You are using a very small-scoped try-with-resources:
try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
returnedObject = (Object) ois.readObject();
}
This code is interpreted as:
Get the input stream and build an ObjectInputStream around it.
Read an object from the object stream
Close the ObjectInputStream.
When you close the ObjectInputStream it automatically closes the InputStream that backs it, which is the socket's input stream. And the documentation of getInputStream says:
Closing the returned InputStream will close the associated socket.
You should make sure the try-with-resources has a bigger scope that covers the entire lifetime of the socket, or avoid using try-with-resources and make sure you close the ObjecInputStream properly when you are done with it or when there is an error.

Error in receiving ObjectInputStream

I am trying to create a client server program where I'm sending an object from client and receiving the object at the server continuously in the while loop.
Client code:
ObjectOutputStream oos = null;
while(true){
WorkerMessageToMaster message = new WorkerMessageToMaster(WorkerTasksStatus.getTaskStatusMap(), WorkerTasksStatus.getTaskStatusReduce());
oos = new ObjectOutputStream(taskManagerSocket.getOutputStream());
oos.writeObject(message);
oos.flush();
Thread.sleep(1000);
}
Server code:
ObjectInputStream ois = null;
while (true ) {
ois = new ObjectInputStream(clientSocket.getInputStream());
WorkerMessageToMaster taskMapObject = (WorkerMessageToMaster)ois.readObject();
System.out.println("Connection from: "+clientSocket.getInetAddress().getHostAddress().toString());
}
When I try to run this code on my local system It runs normally, but when I try to run the client and server in different machines(different Ips) I get the following error.
java.io.StreamCorruptedException: invalid stream header: 74000432
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at master.MasterAnalyzer.heartBeat(MasterAnalyzer.java:58)
at master.MasterAnalyzer.run(MasterAnalyzer.java:80)
at java.lang.Thread.run(Thread.java:745)
I am confused at this erratic behavior as Im sending the stream through the client socket established with the server in a while loop and receiving it on the same socket connection accepted at the server and It seems to be working fine on local host.
Thank you for your help
You create a new stream for each object. Only create one output and one input stream. Object streams send header data which is maybe corrupted when you create a new stream.

How to handle sending multiple messages over a socket connection?

I'm a bit of a beginner programmer so it's possible this is quite obvious and I'm overlooking the answer. But on to the question.
I have a two-part program (its a little more complicated than this example, but the situation is the same). The program has multiple messages fired between the client and the server. I have a PrintWriter on the server-side to send messages to the client, and on the client, I have a BufferedReader to read the messages sent.
When this example is run, I'm given two lines as output. The first message is both messages, and the second is NULL. What I am wondering is if there is a way to basically halt the server until I am ready for the second message, so that I can do something on the client-side before the second message is sent.
I am hoping to not use Thread.Sleep, as I would rather the Server wait around until the Client says it is ready.
This is the client:
public class Client{
public void run(){
Socket socket = null;
InputStream in = null;
BufferedReader reader = null;
try{
socket = new socket("LocalHost",1234);
in = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
}
String messageFromServer = "";
try{
messageFromServer=reader.readLine();
}
System.out.println(messageFromServer);
String messageFromServer = "";
try{
messageFromServer=reader.readLine();
}
System.out.println(messagefromServer);
//close everything
}
}
This is the server:
public class Server{
public void run(){
ServerSocket server = null;
Socket client = null;
try{
server = new ServerSocket(1234);
client = server.accept();
}
PrintWriter writer = null;
OutputStream out = null;
try{
out = client.getOutputStream();
writer = new PrintWriter(out, true);
}
writer.write("Hi I'm a server");
//do some stuff that takes some time, user input, etc. etc.
writer.write("I'm still a server");
//close everything
}
Thanks :)
The problem with the way you currently have you code is the fact that you are using a BufferedReader, but the server is not terminating it's messages with a new line.
When you close the writer, the client is reaching the EOF or EOS and unblocking the read so it appears that both strings are being sent at once...
If you do something like...
writer.write("Hi I'm a server\n");
// This will force the message to be written to the client and picked up ;)
writer.flush();
writer.write("I'm still a server\n");
writer.flush();
Then you will get the messages seperatly...
You can use ObjectInputStream to read Objects instead of Strings.
This way you will read only one Message(String in your case) every call to ObjectInputStream.readObject();
BTW you can read the first message, "do something" and then read the second message. you don't have to read all of the sent messages at once.
If there are no other messages, then your thread will be blocked when trying to read an object from the ObjectInputStream.
Use it like:
ObjectInputStream inputStream = new ObjectInputStream( socket.getInputStream() )

Android Socket InputStream problem

I have a server written in VB, it sends data to clients in periods of 3 seconds. I've written a client Java code like this:
class Commu extends Thread {
Socket socket;
InputStream inputStream;
OutputStream outputStream;
public Commu() {
try {
socket=new Socket();
socket.connect(new InetSocketAddress("192.168.0.1", 1234)));
inputStream=socket.getInputStream();
outputStream=socket.getOutputStream();
this.start();
} catch(Exception e) {
System.out.println(e);
}
}
public void run() {
while(true) {
byte[] buffer=new byte[1024];
inputStream.read(buffer);
System.out.println(buffer[0]);
}
}
}
It works fine on my desktop, it prints message whenever the VB server sends message.
It works on Android, but the inputStream read only once, and then get stuck; If I want to read more data, I have to use outputStream to send some data, then inputStream will read once, and get stuck again. That is really strange, could anyone tell me why?
There is no problem in System.out.print(), because DDMS can show it, I promise! The problem is inputStream should not read only once, it should read when data comes. But it didn't , it read only once.
Even if, I only print one byte from the buffer, it get stuck on Android. It works very well on desktop, but get stuck on Android.
That's a wierd piece of code. You don't check the return value of read() for -1, i.e. EOS, and you only display the first byte of the data received and throw the rest away.

Categories

Resources