Send a zero-data TCP/IP packet using Java

2019-05-07 11:13发布

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.

2条回答
三岁会撩人
2楼-- · 2019-05-07 11:19

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.

查看更多
倾城 Initia
3楼-- · 2019-05-07 11:36

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

查看更多
登录 后发表回答