Problem with SocketChannel.write ()

The problem here is that I see that the data is being written to the socket, but it is NOT ALWAYS sent.

Here is the sniplet of code

ByteBuffer writeBuffer = ByteBuffer.allocate(8192); writeBuffer.clear(); writeBuffer.put("heartbeat".getBytes()); writeBuffer.flip(); LOG.debug("is connected: " + socketChannel.isConnected()); int bytesWritten = 0; if (key.isWritable()) { while (writeBuffer.hasRemaining()) { bytesWritten += socketChannel.write(writeBuffer); } } 

I use TCPMon to find out if the actual data is written to the socket - WHICH.

But using WireShark (another network monitoring tool), I do not see the packet passing through the network adapter.

Any help would be appreciated

+4
source share
2 answers

In any case, your code is incorrect. If the entry returns zero, the socket send buffer is full, so you should register OP_WRITE and return to the selection loop, and not waste time disconnecting until the place appears again. Your current technology is starving on other service channels and wasting CPU cycles.

In addition, testing isConnected() is currently useless. It. You have connected it. This method tells you the status of the socket, not the connection.

+5
source

Try the following:

 /** * @param socketChannel * @param buf * @return no. of bytes written to the socket * @throws IOException */ public static int writeByteBuffer(SocketChannel socketChannel, ByteBuffer buf) throws IOException { boolean blocking = socketChannel.isBlocking(); Selector selector = Selector.open(); int totalWritten = 0; try { socketChannel.configureBlocking(false); // pass SelectionKey.OP_READ | SelectionKey.OP_WRITE for read and // write socketChannel.register(selector, SelectionKey.OP_WRITE); selector.select(); Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); outerOfWriting: while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); boolean writable = key.isWritable(); if (writable) { SocketChannel channel = (SocketChannel) key.channel(); boolean hasRemaining = false; while (hasRemaining = buf.hasRemaining()) { int written = channel.write(buf); totalWritten += written; if (written == 0) { selector.select(); selectedKeys = selector.selectedKeys(); keyIterator = selectedKeys.iterator(); continue outerOfWriting; } } if (!hasRemaining) { key.cancel(); break; } } } } finally { try { selector.close(); socketChannel.configureBlocking(blocking); } catch (IOException e) { e.printStackTrace(); } } return totalWritten; } public static void main(String[] args) { try { ByteBuffer writeBuffer = ByteBuffer.allocate(8192); writeBuffer.clear(); writeBuffer.put("heartbeat".getBytes()); writeBuffer.flip(); SocketChannel socketChannel = null;//initialize writeByteBuffer(socketChannel, writeBuffer); } catch (IOException e) { e.printStackTrace(); } } 
-1
source

All Articles