Hi,
I am unable to read data from socket channel .. I am trying write and read data from server ...
key.isReadable() is returning false ....
How do I read data from server ....
Here is my code ...
public
String getResponse(byte[] request) throws Exception {
StringBuffer sbResponse = null;
byte[] array = null;
String str = null;
SocketChannel client = SocketChannel.open();
client.configureBlocking(false);
client.connect(new java.net.InetSocketAddress("xxx.xxx.xxx.xxx", yyyyy));
// Create selector
Selector selector = Selector.open();
// Record to selector (OP_CONNECT type)
SelectionKey clientKey = client.register(selector,SelectionKey.OP_CONNECT | SelectionKey.OP_READ);
// Waiting for the connection
if(selector.select(50) > 0) {
// Get keys
Set keys = selector.selectedKeys();
Iterator i = keys.iterator();
// For each key...
while (i.hasNext()) {
SelectionKey key = (SelectionKey) i.next();
// Remove the current key
i.remove();
// Get the socket channel held by the key
SocketChannel channel = (SocketChannel) key.channel();
// Attempt a connection
if (key.isConnectable()) {
// Close pendent connections
if (channel.isConnectionPending())
channel.finishConnect();
// Write data into channel
ByteBuffer requestByteBuffer = ByteBuffer.wrap(request);
channel.write(requestByteBuffer);
requestByteBuffer.clear();
}
if(key.isReadable()) {
//Allocates a new byte buffer
ByteBuffer buffer1 = ByteBuffer.allocate(100);
sbResponse = new StringBuffer();
try {
while (channel.read(buffer1) > 0) {
array = new byte[100];
buffer1.position(0);
buffer1.get(array, 0, 100);
str = new String(array);
sbResponse.append(str);
buffer1.clear();
}
} catch (IOException e) { e.printStackTrace(); }
}
if(channel != null) channel.close();
} // end while
} // end if
return sbResponse.toString();
}
Thanks,
suchi.