I am not sure if your ops is set correctly. If that socket is used to listening, you may need to set it as SelectionKey.OP_ACCEPT
, and read data as SelectionKey.OP_READ
. https://github.com/harleyw/NioSocketLib/ could be referred for Java nio socket.
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
public class NIOServer {
private static Selector selector = null;
public static void main(String[] args)
{
try {
selector = Selector.open();
// We have to set connection host,port and
// non-blocking mode
ServerSocketChannel serverSocketChannel
= ServerSocketChannel.open();
ServerSocket serverSocket
= serverSocketChannel.socket();
serverSocket.bind(
new InetSocketAddress("localhost", 8089));
serverSocketChannel.configureBlocking(false);
int ops = serverSocketChannel.validOps(); <<<<<<<<<<<<<<<
serverSocketChannel.register(selector, ops,
null);
while (true) {
selector.select();
Set<SelectionKey> selectedKeys
= selector.selectedKeys();
Iterator<SelectionKey> i
= selectedKeys.iterator();
while (i.hasNext()) {
SelectionKey key = i.next();
if (key.isAcceptable()) {
// New client has been accepted
handleAccept(serverSocketChannel,
key);
}
else if (key.isReadable()) {
// We can run non-blocking operation
// READ on our client
handleRead(key);
}
i.remove();
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}