我正在编写一个小型客户端库来帮助我处理我正在处理的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
}
}
谢谢!
答案 0 :(得分:1)
ListeningExecutorService
不是获取/创建ListenableFuture
的唯一方法。你看过SettableFuture
了吗?它可能会有所帮助。