使用Guava作为套接字客户端库

时间:2014-06-12 17:54:33

标签: java sockets guava

我正在编写一个小型客户端库来帮助我处理我正在处理的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
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

ListeningExecutorService不是获取/创建ListenableFuture的唯一方法。你看过SettableFuture了吗?它可能会有所帮助。

相关问题