简体   繁体   English

Java套接字无法发送两个字节数组

[英]Java socket unable to send two byte arrays

I am trying to send two byte arrays over a Java socket. 我正在尝试通过Java套接字发送两个字节数组。 I have captured the data via wireshark and it shows that the first byte array sends; 我已经通过Wireshark捕获了数据,它表明第一个字节数组已发送; the second, however, doesn't send at all. 但是,第二个根本不发送。 I am using Linux Mint and Oracle's JRE (not OpenJDK). 我正在使用Linux Mint和Oracle的JRE(不是OpenJDK)。

byte[] packet_one = new byte[] {(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x50};
byte[] packet_two = new byte[] {(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x78};
Socket sck;
DataInputStream dis;
DataOutputStream dos;

try {
sck = new Socket(IP_ADDRESS,PORT);    
dis = new DataInputStream(sck.getInputStream());     
dos = new DataOutputStream(sck.getOutputStream());

int recv_header = dis.ReadInt(); // This receives the correct response.

dos.write(packet_one); // Sends fine.

dos.write(packet_two); //Does not send.

int data_length = dis.readInt(); // No more data received.

}catch(Exception e) {
 System.out.println("Error: " + e.getMessage());    
}

So, dos.write(packet_one) works (confirmed by wireshark). 因此,dos.write(packet_one)有效(由wireshark确认)。 Writing packet_two doesn't work. 编写packet_two不起作用。 The data_length returns 0 since I don't receive anymore data either. 由于我也未收到任何数据,因此data_length返回0。 No errors or exceptions get caught. 没有错误或异常被捕获。

I have also tried using dos.flush(), but it doesn't make a difference. 我也尝试过使用dos.flush(),但没有任何区别。

Any ideas on why this may be the case? 关于为什么可能会这样的任何想法?

Maybe you're exiting the program before there's time to send the buffered bytes? 也许您是在没有时间发送缓冲字节之前退出程序的?

Perhaps if you add something like: 也许如果您添加如下内容:

for (;;) {
    final byte x = dis.readByte();
    System.out.println("got byte: " + (x & 0xFF));
}

the program won't exit, and you'll also see if there are more bytes that the server sent back. 该程序将不会退出,您还将看到服务器是否还发送了更多字节。 Might offer clues. 可能提供线索。

And, in case you don't know, readInt() reads for bytes and returns an int made from those bytes, which is 0 if all the for bytes read are zero. 并且,如果您不知道,readInt()读取字节并返回由这些字节组成的int,如果所有读取的for字节均为零,则为0。 So your comment 'No more data received.' 因此,您的评论是“没有收到更多数据”。 feels a bit ambiguous. 感觉有点big昧。

You could also try inserting a 您也可以尝试插入

sck.setTcpNoDelay(true);

after creating the socket. 创建套接字后。 Writes should then go on the network immediately. 然后应立即在网络上写入。 I think. 我认为。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM