Hi I am trying to implements a simple Java NIO server; which registers the socketChannel with the selector. Hence I wish to listen to client and send some response back. After the socketChannel is registered with the selector, even if client(non NIO) sends some data, Server is not able to read; howerver the key generated is still being iterated.
Detailed View: Server Side:
**First thread**:
public void run() { while (true) {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(true);
serverSocketChannel.socket().bind(inetAdressOfServer);
SocketChannel clientChannel = serverSocketChannel.accept();
new Listener("").addSocketChannel(clientChannel);
}}
**Second Thread**:
static Selector selector = Selector.open();
public boolean addSocketChannel(SocketChannel clientChannel) {
SelectionKey key = clientSocketChannel.register(selector, selector.OP_READ|SelectionKey.OP_WRITE);
key.attach(new ChannelCallback(clientSocketChannel));
return key.isValid();
}
public void run() {
Set keysSet = selector.keys();
Iterator i = keysSet.iterator();
while (i.hasNext()) {
SelectionKey key = (SelectionKey) i.next();
}
if (key.isReadable()) {
//read and do something
}
}
Client Side:
Socket socket = new Socket(serverIP, serverPort);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeBytes(str + "\n");
NB: When done in single thread, the same program works, but when implemented in the manner mentioned above causes it not to listen to client. Please help me to resolve this issue.