0

一段时间以来,我一直在尝试使用 NIO SocketChannels,但我对写入 SocketChannel 感到困惑。以下代码来自我的客户:

    public class nbClient {

/**
 * @param args
 */
static int id;
static int delay = 1000;
static int port;
public static void main(String[] args) throws Exception{

    if (args.length > 0){
        id = Integer.parseInt(args[0]);
        port = Integer.parseInt(args[1]);

    }
    else{
        id = 99;
        port = 4444;
    }
    // Create client SocketChannel
    SocketChannel client = SocketChannel.open();

    // nonblocking I/O
    client.configureBlocking(false);

    // Connection to host port 8000
    client.connect(new java.net.InetSocketAddress("localhost",port));       

    // Create selector
    Selector selector = Selector.open();

    //SelectionKey clientKey = client.register(selector, SelectionKey.OP_CONNECT);
    SelectionKey clientKey = client.register(selector, client.validOps());

    // Waiting for the connection

    while (selector.select(1000) > 0) {

      // Get keys
      Set keys = selector.selectedKeys();
      Iterator i = keys.iterator();

      // For each key...
      while (i.hasNext()) {
        SelectionKey key = (SelectionKey)i.next();

        // Remove the current key
        i.remove();      

        // Get the socket channel held by the key
        SocketChannel channel = (SocketChannel)key.channel();

        // Attempt a connection
        if (key.isConnectable()) {

          // Connection OK
          System.out.println("Server Found");

          // Close pendency connections
          if (channel.isConnectionPending())
            channel.finishConnect();
          //channel.close();

          channel.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ);

        }
        if (key.isWritable()){
            System.out.println("Ready for writing");

              // Write on the buffer
              ByteBuffer buffer = null;
              int counter = 0;                
                buffer = 
                  ByteBuffer.wrap(
                    new String(" This is a very long message from Client " + id + " that should exceed the bufer by a bit").getBytes());
                int outBytes = channel.write(buffer);
                System.out.println(channel.isConnectionPending());
                System.out.println(outBytes);
                buffer.clear();
                counter++;

        }

        if (key.isReadable()){
            System.out.println("Ready for reading");
        }

      }
    }

}

}

当我尝试向频道写信时,我的问题必须解决。每当这部分代码运行时,它都会循环无数次,在每次迭代期间将数据写出,而无需等待服务器处理它。当我用我的代码运行调试器时,服务器似乎能够赶上并处理传输(客户端不断重新发送请求,但至少服务器显示传输的字节)。但是,当代码按原样运行而没有任何强制延迟时,客户端代码运行了几十次,然后连接断开,而服务器似乎忽略了传输。这是我的服务器代码部分 - 请注意,它是从 Runnable 类运行的:

try {
            readwriteSelector.select();
            // Once the event occurs, get keys
            Set<SelectionKey> keys = readwriteSelector.selectedKeys();
            Iterator<SelectionKey> i = keys.iterator();     


            // For each keys...
            while(i.hasNext()) {

              // Get this most recent key
              SelectionKey key = i.next();      

              if (key.isReadable()){
                  System.out.println("Is Readable");
              }

              if (key.isWritable()){
                  System.out.println("Is Writable");
                  SocketChannel client = (SocketChannel) key.channel();
                  buf.clear();

                  int numBytesRead = client.read(buf);

                  if (numBytesRead == -1){
                        client.close();
                    }
                    else {
                        buf.flip();
                        byte[] tempb = new byte[buf.remaining()];

                        buf.get(tempb); 

                        String s = new String(tempb);

                        System.out.println(s);
                    }
              }

              // Remove the current key
              i.remove();
              //readwriteSelector.selectedKeys().clear();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

我知道这是很多代码,但此时我无法确定问题出在哪里。任何人都可以推断为什么客户端和服务器似乎无法通信,尽管如果我强制延迟传输会正常进行?

谢谢。

4

1 回答 1

2

服务器read()方法也应该在循环中。SocketChannel.read()将读取到缓冲区的大小,但可能会读取更少,包括 0 字节。

替换块启动

int numBytesRead = client.read(buf);

   StringBuilder msg = new StringBuilder();
   for (;;) {
    int numBytesRead = client.read(buf);
    if (numBytesRead==-1)
        break;
    if (numBytesRead>0) {
        buf.flip();
        byte[] tempb = new byte[buf.remaining()];
        buf.get(tempb); 
        String s = new String(tempb);
        msg.append(s);
    }
   }
   client.close();
   System.out.prinltn(msg);
于 2011-04-17T06:43:16.203 回答