为什么在java socket中,我们不能连续发送消息?

时间:2014-10-08 04:44:08

标签: java sockets

这是我的粗略计划。我有两个客户端,一个服务器,我想得到结果
Test1的
Test2的
...
...
但它只给我Test1 ......

我尝试在服务器和接收方法中添加回复方法。就像我在下面提到的那样,问题就解决了。结果就像是 Test1的
Test1的
Test2的
Test2的
Test1的
TEST2

为什么我必须添加此回复方法?

服务器:

ByteBuffer readBuffer = ByteBuffer.allocate(1024);
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
while ( keys.hasNext() ) {
    SelectionKey key = (SelectionKey)keys.next();
    keys.remove();

    if (!key.isValid()) 
        continue;

    if (key.isReadable()) {
        SocketChannel nsc = (SocketChannel) key.channel();

                     // clear buffer for reading
        readBuffer.clear();
        int nBytes = nsc.read(readBuffer);
        DataInputStream ist = new DataInputStream (
                              new ByteArrayInputStream(readBuffer.array()));
        String info = ist.readUTF();
        switch (info) {
            case TAKE:
                System.out.println("Test1");
                /*writeBuffer.clear();
                  writeBuffer.putInt(1);
                  writeBuffer.flip();
                  nsc.write(writeBuffer);*/ // the reply method
                break;
            case BUN:
                System.out.println("Test2");
                  break;
          }
      }
  }

客户端:

DataOutputStream out = new DataOutputStream(sock.getOutputStream());
DataInputStream in = new DataInputStream(sock.getInputStream());

do {
    try {
        out.writeUTF("TAKE ");
        //in.readInt(); the receive method
        out.writeUTF("BUN ");

        Thread.sleep(id + 1);
     } catch (IOException ioe) {
         sock.close();
         throw ioe;
     } catch (InterruptedException ie) {
         Thread.currentThread().interrupt();
     }
 } while (true);

1 个答案:

答案 0 :(得分:0)

使用ByteBuffer.array()无效:您必须flip()缓冲区和get(),而不是像现在这样忽略其位置和限制。或者使用ByteArrayOutputStreamposition()构建limit()作为偏移和长度参数。