CharBuffer view on ByteBuffer and No Bytes Written to SocketChannel
Hi,
I've actually got two problems that might be connected. I'm new to the java.nio.* package. I wanted to try SocketChannel's to see if I could improve performance.
If this isn't the appropriate place for java.nio questions, just let me know.
My first problem is that I create a ByteBuffer by allocating x number of bytes. These bytes are the length of the message I want to send to the server. Then, I attempt to get a CharBuffer view of the ByteBuffer (buffer.asCharBuffer). For some reason, it only returns a CharBuffer with half the capacity of the ByteBuffer. So of course, when I stuff my String into the CharBuffer, it doesn't fit.
Well, I hack that and make the ByteBuffer twice as big. Which brings me to problem two, my SocketChannel does not write any bytes to the server when told to.
Here's the code (with hack):
ByteBuffer buf;
CharBuffer cbuf;
SocketChannel sockChan;
try{
int msgLength = message.length();
logger.info("Message length=" + msgLength);
logger.info("message length in bytes=" + message.getBytes().length);
buf = ByteBuffer.allocateDirect(msgLength*2);
logger.info("position=" + buf.position());
logger.info("capacity=" + buf.capacity());
logger.info("limit=" + buf.limit());
cbuf = buf.asCharBuffer();
logger.info("capacity of cbuf=" + cbuf.capacity());
cbuf.put(message);
buf.flip();
sockChan = SocketChannel.open();
sockChan.configureBlocking(true);
sockChan.socket().setSoTimeout(TIMEOUT_MS);
logger.info("socket configured");
sockChan.connect(new InetSocketAddress(ipAddress, portNumber));
int numBytesWritten = sockChan.write(buf);
logger.info("connected and wrote message. NumBytes writen=" + numBytesWritten);
if (numBytesWritten != msgLength){
//throw error
logger.error("The number of bytes written do not match the " +
"message length (in bytes).");
}
}catch (IOException e1){
// TODO Auto-generated catch block
e1.printStackTrace();
}
And the console outputs the following:
[Dec 13, 11:46:17] INFO - Message length=50
[Dec 13, 11:46:17] INFO - message length in bytes=50
[Dec 13, 11:46:17] INFO - position=0
[Dec 13, 11:46:17] INFO - capacity=100
[Dec 13, 11:46:17] INFO - limit=100
[Dec 13, 11:46:17] INFO - capacity of cbuf=50
[Dec 13, 11:46:17] INFO - socket configured
[Dec 13, 11:46:17] INFO - connected and wrote message. NumBytes writen=0
[Dec 13, 11:46:17] ERROR - The number of bytes writtendo not match the message length (in bytes).
My batch program freezes at this point. Don't know why it does that either.
Thanks for any help,
CowKing

