papafe
papafe

Reputation: 3070

Blocking read from an input TCP socket

I am currently working on a project for a distributed systems course where we have to implement a small sensor network in java. The sensors send the temperature every x seconds to an admin node (that is also a sensor), that records them. Upon request, an user node connects to the admin node and receives the mean of the detected temperatures. One of the issues is that the admin node can "fail". Before failing it actually sends a message to the user node, that needs to send a special packet to one of the other regular nodes that will become the new admin. The user node communicates with the admin with a TCP connection trough which it sends a "request" packet and receives a packet containing the temperature. I am currently using java.net.socket to implement this.

The problem comes when the admin fails. In normal condition, could create a new thread that waits for this "fail" message from the server and then creates a new socket with the newly selected admin node. But, if the admin fails before it sends a message in response to a user request, the user node will be indefinitely waiting, because it is reading from an input stream.

In particular, I am using the following lines to create the socket and the input stream:

   this.socket = new Socket(this.serverAddress,this.serverPort);
   this.in = new DataInputStream(socket.getInputStream());

and the following line in an while loop to read the response temperature.

   String data = in.readUTF();

How would you suggest to handle this situation?

Also, I was thinking to use the same TCP connection for receiving the "fail" message from the admin node. How can I support this?

Upvotes: 1

Views: 1018

Answers (2)

user207421
user207421

Reputation: 310883

Just set a read timeout via Socket.SetSoTimeout().

Upvotes: 1

Oscar
Oscar

Reputation: 1

Have you considered looking into Apache MINA? It's a library for Java NIO.

Java NIO is a non-blocking socket package containing classes to communicate with either TCP or UDP

Upvotes: 0

Related Questions