C
conrad
It seems either non-blocking sockets can be used or
blocking sockets with two threads, one for reading and
the other for writing. Is this correct?
My next question is this, I was messing about with
Java's non blocking sockets and registered the
read and write operations with the socket channel.
client.configureBlocking(false);
Selector selector = Selector.open();
client.register(selector, SelectionKey.OP_READ |
SelectionKey.OP_WRITE);
If a read is set, then I call my read function which chiefly
does the following(I'm keeping it very simple at the moment
and will add checks for other kinds of errors later):
ByteBuffer buffer = ByteBuffer.allocateDirect (1024);
buffer.clear();
while((count = socketChannel.read(buffer)) > 0) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
What's peculiar is that after reading, when it is ready
for a write, I call my write function and send data to
the server:
ByteBuffer buffer = ByteBuffer.wrap("myusername\r\n".getBytes());
buffer.flip();
socketChannel.write(buffer);
Then, the next read will return what I have written to the server.
How is that possible? Looking into the use of non-blocking
sockets more deeply, it seems Java structures the stream
between client and server by doing the following:
size_of_data + the_data
At least, based on some Java I was looking at.
Could anyone elaborate on this? I clearly need
a Java book on non-blocking input/output but
for the meantime would greatly appreciate if
anyone could clarify the above.
Thanks.
blocking sockets with two threads, one for reading and
the other for writing. Is this correct?
My next question is this, I was messing about with
Java's non blocking sockets and registered the
read and write operations with the socket channel.
client.configureBlocking(false);
Selector selector = Selector.open();
client.register(selector, SelectionKey.OP_READ |
SelectionKey.OP_WRITE);
If a read is set, then I call my read function which chiefly
does the following(I'm keeping it very simple at the moment
and will add checks for other kinds of errors later):
ByteBuffer buffer = ByteBuffer.allocateDirect (1024);
buffer.clear();
while((count = socketChannel.read(buffer)) > 0) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
What's peculiar is that after reading, when it is ready
for a write, I call my write function and send data to
the server:
ByteBuffer buffer = ByteBuffer.wrap("myusername\r\n".getBytes());
buffer.flip();
socketChannel.write(buffer);
Then, the next read will return what I have written to the server.
How is that possible? Looking into the use of non-blocking
sockets more deeply, it seems Java structures the stream
between client and server by doing the following:
size_of_data + the_data
At least, based on some Java I was looking at.
Could anyone elaborate on this? I clearly need
a Java book on non-blocking input/output but
for the meantime would greatly appreciate if
anyone could clarify the above.
Thanks.