有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java异步NIO:同一个客户端向服务器发送多条消息

关于JavaNIO2

假设我们有以下内容来倾听客户的请求

asyncServerSocketChannel.accept(null, new CompletionHandler <AsynchronousSocketChannel, Object>() {
    @Override
    public void completed(final AsynchronousSocketChannel asyncSocketChannel, Object attachment) {
         // Put the execution of the Completeion handler on another thread so that 
         // we don't block another channel being accepted.
         executer.submit(new Runnable() {
             public void run() {
                 handle(asyncSocketChannel);
             }
         });

         // call another.
         asyncServerSocketChannel.accept(null, this);
     }

     @Override
     public void failed(Throwable exc, Object attachment) {
         // TODO Auto-generated method stub
     }
});

此代码将接受一个客户端连接进程,然后再接受另一个。 为了与服务器通信,客户端打开一个AsyncSocketChannel并触发消息。 然后调用Completion handler completed()方法

然而,这意味着如果客户端想要在同一个AsyncSocket实例上发送另一条消息,它就不能

它必须创建另一个AsycnSocket实例——我认为这意味着另一个TCP连接——这是性能问题

有什么办法吗

或者换一种方式来回答这个问题,你知道如何让同一个asyncSocketChannel接收多个CompleteOnHandler completed()事件吗

编辑: 我的处理代码是这样的

public void handle(AsynchronousSocketChannel asyncSocketChannel) {
    ByteBuffer readBuffer = ByteBuffer.allocate(100);
    try {
        // read a message from the client, timeout after 10 seconds 
        Future<Integer> futureReadResult = asyncSocketChannel.read(readBuffer);
        futureReadResult.get(10, TimeUnit.SECONDS);
        String receivedMessage = new String(readBuffer.array());

        // some logic based on the message here...               

        // after the logic is a return message to client
        ByteBuffer returnMessage = ByteBuffer.wrap((RESPONSE_FINISHED_REQUEST + " " + client
                 + ", " + RESPONSE_COUNTER_EQUALS + value).getBytes());
        Future<Integer> futureWriteResult = asyncSocketChannel.write(returnMessage);
        futureWriteResult.get(10, TimeUnit.SECONDS);
   } ...

就是这样,我的服务器从异步通道读取一条消息并返回一个答案。 客户端会一直阻塞,直到得到答案。但这没关系。我不在乎客户是否阻止

完成后,客户端尝试在同一异步通道上发送另一条消息,但它不起作用


共 (0) 个答案