Send a zero-data TCP/IP packet using Java

别说谁变了你拦得住时间么 提交于 2019-12-07 07:51:10

问题


My goal is to send a TCP packet with empty data field, in order to test the socket with the remote machine.

I am using the OutputStream class's method of write(byte[] b). my attempt:

outClient = ClientSocket.getOutputStream();
outClient.write(("").getBytes());

Doing so, the packet never show up on the wire. It works fine if "" is replaced by " " or any non-zero string.

I tried jpcap, which worked with me, but didn't serve my goal. I thought of extending the OutputStream class, and implementing my own OutputStream.write method. But this is beyond my knowledge. Please give me advice if someone have already done such a thing.


回答1:


If you just want to quickly detect silently dropped connections, you can use Socket.setKeepAlive( true ). This method ask TCP/IP to handle heartbeat probing without any data packets or application programming. If you want more control on the frequency of the heartbeat, however, you should implement heartbeat with application level packets.

See here for more details: http://mindprod.com/jgloss/socket.html#DISCONNECT




回答2:


There is no such thing as an empty TCP packet, because there is no such thing as a TCP packet. TCP is a byte-stream protocol. If you send zero bytes, nothing happens.

To detect broken connections, short of keepalive which only helps you after two hours, you must rely on read timeouts and write exceptions.



来源:https://stackoverflow.com/questions/10693570/send-a-zero-data-tcp-ip-packet-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!