我正在编写一个小型客户端库,以帮助我处理正在开发的Android项目。因此,我现在正在学习番石榴,我有点被卡住了。
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
了吗?这可能会有所帮助。