1

I am having a problem with SocketChannel in a client-server java application.

In the server, first of all, I initialize the selector:

Selector selector = null;
try{
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(5000));
    serverSocketChannel.configureBlocking(false);

    selector = Selector.open();
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch(IOException e){
    e.printStackTrace();
    return;
}

And then I start a while:

while(true) {
    try {
        selector.select();
    } catch (IOException ex) {
        ex.printStackTrace();
        break;
    }
    Set<SelectionKey> readyKeys = selector.selectedKeys();
    Iterator<SelectionKey> iterator = readyKeys.iterator();
    while (iterator.hasNext()) {
        SelectionKey key = iterator.next();
        iterator.remove();
        try {
            if (key.isAcceptable()) {
                ServerSocketChannel server = (ServerSocketChannel) key.channel();
                SocketChannel clientChannel = server.accept();
                clientChannel.configureBlocking(false);
                clientChannel.register(selector, SelectionKey.OP_READ);
            } else if (key.isReadable()) {
                readFunction((SocketChannel)key.channel())
        }
    }
}

Now I should develop the readFunction. I'd want to send data between client and server with a string (Json) but since they are not blocking I don't know if I can do it without sending the string's size before the string.

Can someone help me?

Lorenzo
  • 215
  • 4
  • 10
  • convert Json String to` ByteBuffer` and call `SocketChannel.write` method to send,to you try this? – TongChen Mar 11 '19 at 02:50
  • @TongChen the problem is that I don't know a priori how many writes should I do – Lorenzo Mar 11 '19 at 03:03
  • Assume you Json string length is 245,and your ByteBuffer capacity is 100,you need to send three times.There is some work need client and server to do,combine three part of string into one.Do I understand what you mean? – TongChen Mar 11 '19 at 03:12
  • Yes, you right but the server doesn't know that it has to receive 245 bytes. In fact, my original question was if I could send a string without sending the string size before – Lorenzo Mar 11 '19 at 03:20
  • 1
    You need a way to communicate to the destination when a chunk of data starts and ends. One option is to send the size before hand. Another option is to have a terminating value sent at the end. Basically, you need a protocol that's understood by both the server and client. – Slaw Mar 11 '19 at 03:51
  • @Lorenzo this is a common problem,since TCP is a Stream protocol so we need Encode/Decode , If you want write by yourself you can refe [netty](https://netty.io/4.1/api/index.html) – TongChen Mar 11 '19 at 04:59

0 Answers0