简体   繁体   English

阻止从输入TCP套接字读取

[英]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. 我目前正在从事一个分布式系统课程的项目,在该项目中,我们必须使用Java实现小型传感器网络。 The sensors send the temperature every x seconds to an admin node (that is also a sensor), that records them. 传感器每隔x秒将温度发送到一个管理节点(也是一个传感器),并对其进行记录。 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. 用户节点通过TCP连接槽与管理员通信,该节点发送“请求”数据包并接收包含温度的数据包。 I am currently using java.net.socket to implement this. 我目前正在使用java.net.socket来实现这一点。

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. 在while循环中的下一行读取响应温度。

   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. 另外,我还在考虑使用相同的TCP连接来接收来自管理节点的“失败”消息。 How can I support this? 我该如何支持?

只需通过Socket.SetSoTimeout()设置读取超时。

Have you considered looking into Apache MINA? 您是否考虑过研究Apache MINA? It's a library for Java NIO. 它是Java NIO的库。

Java NIO is a non-blocking socket package containing classes to communicate with either TCP or UDP Java NIO是一个非阻塞套接字包,包含用于与TCP或UDP通信的类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM