如何在java中管理AsynchronousSocketChannel或AsynchronousServerSocketChannel

时间:2016-04-02 15:06:06

标签: java sockets nio

我正在使用Java NIO编写。我的模块就像一个人将一些数据作为服务器(使用AsynchronousServerSocketChannel)工作,然后将此数据发送到由AsynchronousSocketChannel作为客户端创建的另一个完全不同的连接

public void completed(AsynchronousSocketChannel result, Void attachment) {
        asynchronousServerSocketChannel.accept(null, this);
        try {
           System.out.println("Incoming connection from: " + result.getRemoteAddress());
           //transmitting data
           while (result.read(buffer).get() != -1) {
                  buffer.flip();
                  result.write(buffer).get();
                  ClientwithFuture anotherDiffrentSocketChannel = new ClientwithFuture(buffer);

使用最后一行是不合逻辑的,因为它会导致服务器中断并运行AsynchronousSocketChannel。在您看来,这个问题可能是一个很好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

好的,我定义了两个线程,其中一个我写了AsynchronousSocketChannel,另一个写了AsynchronousServerSocketChannel。为了在这两个线程之间进行通信,我使用了一些共享变量,并解决了这个问题。