SocketChannel.write()编写问题 [英] SocketChannel.write() writing problem

查看:2280
本文介绍了SocketChannel.write()编写问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的问题是我可以看到数据正被写入套接字,但它并不总是被发送。

The issue here is I can see that the data is being written out to the socket but it is not ALWAYS being sent.

这是一个代码片段

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);
    }
}

我使用TCPMon查看实际数据是否写入插座 - 它的作用。

I use TCPMon to see if the actual data gets written out to the socket - WHICH it does.

但是使用WireShark(另一种网络监控工具)我看不到数据包通过网卡。

But using WireShark (another network monitoring tool) I cannot see the packet going through the NIC.

任何帮助都将不胜感激

推荐答案

你的代码无论如何都是错的。如果写入返回零,则套接字发送缓冲区已满,因此您应该注册OP_WRITE并返回到选择循环,而不是浪费时间旋转直到再次有空间。您现有的技术使其他服务渠道匮乏并浪费CPU周期。

Your code is wrong anyway. If the write returns zero the socket send buffer is full, so you should register OP_WRITE and return to the select loop, rather than waste time spinning until there is room again. Your present technique starves the other channels of service and wastes CPU cycles.

另外,在此测试 isConnected()这点是徒劳的。它是。你连接了它。该方法告诉您套接字的状态,而不是连接。

Also, testing isConnected() at this point is futile. It is. You connected it. That method tells you about the state of the socket, not the connection.

这篇关于SocketChannel.write()编写问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆