Here One server and one client is there. And communication has been maintained by selectable Channel.
like–
Server —
SelectionKey selectKey = channel.register(this.selector,
SelectionKey.OP_ACCEPT);
while (selectKey.selector().select() > 0) {
Set<SelectionKey> selectedKeys = this.selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isAcceptable()) {
ServerSocketChannel nextChannel = (ServerSocketChannel) key
.channel();
SocketChannel newChannel = nextChannel.accept();
newChannel.configureBlocking(false);
if (!newChannel.isRegistered()) {
SelectionKey selectionKey = newChannel.register(
this.selector, SelectionKey.OP_READ
| SelectionKey.OP_WRITE);
selectionKey.attach(newChannel);
}
} else if (key.isWritable()) {
SocketChannel attachment1 = (SocketChannel)key.attachment();
ByteBuffer writeBuffer = ByteBuffer.wrap("Hello".getBytes());
attachment1.write(writeBuffer);
System.out.print("Written");
}
}
}
Client :
InetSocketAddress isa = new InetSocketAddress(InetAddress
.getLocalHost(), 4444);
SocketChannel sc = null;
try {
while (true) {
Thread.sleep(10000);
sc = SocketChannel.open();
sc.connect(isa);
ByteBuffer byteBuffer = ByteBuffer.allocate(BUFSIZE);
int nbytes = sc.read(byteBuffer);
byteBuffer.flip();
dbuf.flip();
CharBuffer cb = decoder.decode(byteBuffer);
System.out.println(isa + " : " + cb);
}
The Problem is that every time client read the data up to full size of buffer limit of client instead of sent data limit.
This is the way TCP sockets work — they are a stream of bytes, not a sequence of messages.
You’ll need to design in a higher level protocol so that the receiver can re-discover the message boundaries after it receives the bytes.