有 Java 编程相关的问题?

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

在Java中写入SocketChannel的socket意外重复

一段时间以来,我一直在尝试与NIO Socketchannes合作,但我对向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");
        }

      }
    }

}

}

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

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();
        }

我知道这是一个很大的代码,但在这一点上,我不能指出问题所在。有人能推断出为什么客户机和服务器似乎无法通信,尽管如果我强制延迟,传输会很好地进行吗

谢谢


共 (1) 个答案

  1. # 1 楼答案

    serverread()方法也应该在循环中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);