我正在编写一个小型客户端库来帮助我完成我正在开发的 Android 项目。所以我现在正在学习Guava,有点卡住了。
TCP 服务器有 2 个功能:
- 回复直接询问
- 订阅将来将多次回复的查询
所以我使用 AbstractExecutionThreadService
来监听传入的消息。对于直接查询,我考虑使用 ListenableFuture
,对于订阅消息,我考虑使用 EventBus
。
问题是,要创建 ListenableFuture
,我必须使用 ListeningExecutorService
,而它现在正是我想要的。如果您看到我的代码,run
循环将处理消息,并应以某种方式解析正确的 ListenableFuture
。
那么我如何使 test()
方法返回一个 ListenableFuture
,当数据到达时,它将由 run()
循环解析?
public class StratumClient extends AbstractExecutionThreadService {
private static final Logger log = LoggerFactory.getLogger(StratumClient.class);
private final String host;
private final int port;
private Socket socket;
private DataOutputStream toServer;
private BufferedReader fromServer;
public StratumClient(String host, int port) throws IOException {
this.host = host;
this.port = port;
this.socket = createSocket();
}
protected Socket createSocket() throws IOException {
log.debug("Opening a socket to " + host + ":" + port);
return new Socket(host, port);
}
@Override
protected void startUp() throws Exception {
log.debug("Creating I/O streams to socket: " + socket);
toServer = new DataOutputStream(socket.getOutputStream());
fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
@Override
protected void triggerShutdown() {
try {
socket.close();
} catch (IOException e) {
log.error("Failed to close socket", e);
}
}
@Override
protected void run() throws Exception {
String reply;
log.debug("Start listening to server replies");
while ((reply = fromServer.readLine()) != null) {
log.debug("Got reply from server: " + reply);
// TODO process and dispatch messages
}
log.debug("Finished listening for server replies");
}
public ListenableFuture<String> test(String str) throws IOException {
toServer.writeBytes(str);
return null; // TODO return a ListenableFuture here
}
}
谢谢!
最佳答案
ListeningExecutorService
并不是获取/创建 ListenableFuture
的唯一方法。你看过SettableFuture
吗? ?这可能会有所帮助。
关于java - 使用 Guava 作为套接字客户端库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24190887/