0
    SocketChannel channel = (SocketChannel) key.channel();

    ByteBuffer buffer = ByteBuffer.allocate(1024);
    int numRead = -1;
    try {
        numRead = channel.read(buffer);
        System.out.println("numRead: " + numRead);
    }
    catch (IOException e) { e.printStackTrace();}
    if (numRead == -1) {
        this.dataMap.remove(channel);
        Socket socket = channel.socket();
        SocketAddress remoteAddr = socket.getRemoteSocketAddress();
        System.out.println("Connection closed by client: " + remoteAddr);
        channel.close();
        key.cancel();
        return;
    }
    System.out.println("Got: " + new String(buffer.array(), "windows-1251"));

From the socket reads 1024 bytes of data. In this case all messages are combined, and the last message does not come fully. How do I read the data into a buffer before the message separator '|' ? I want to receive each message individually.

user1221483
  • 431
  • 2
  • 7
  • 20
  • The socket API does this for you. As in it is already in a buffer. – Woot4Moo Jun 28 '12 at 17:47
  • 1
    here is a good read. https://github.com/robbiehanson/CocoaAsyncSocket/wiki/CommonPitfalls talks about what your are asking. the library is for obj-c but the article is about common pitfalls with tcp/udp so its applicable – owen gerig Jun 28 '12 at 17:48

2 Answers2

0

Depends on the protocol, but if the protocol is based on a message separator character, your only option is to read as much as you can without blocking, then scan through the content you read to find the separator. You need to do this in a loop until the connection is closed (or until your side decides to close the connection).

Of course you can read multiple messages at once and even partial messages, so you have to make sure you handle those cases adequately.

biziclop
  • 48,926
  • 12
  • 77
  • 104
  • Unfortunately, this method does not suit me – user1221483 Jun 28 '12 at 17:48
  • That's a shame because there's no other way that would be significantly different. If the protocol was different, for example if every message started with a fixed size header that contains the message length, there would be. – biziclop Jun 28 '12 at 17:50
0

There is no such thing as a message in TCP. It is a byte-stream API. If you want messages you must implement them yourself, via a separator, STX/ETX pair, length word prefix, self-describing protocol, etc.

user207421
  • 305,947
  • 44
  • 307
  • 483