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?