简体   繁体   English

在Java和C ++之间通过TCP发送数据

[英]Sending data over TCP between Java and C++

I have an application that constantly fetches input in Java from a frame buffer and sends it over the wire to a C++ application. 我有一个应用程序,该应用程序不断从帧缓冲区中获取Java输入并将其通过电线发送到C ++应用程序。

I am having issues on the receiver side. 我在接收器端遇到问题。 I am trying to send one packet (or at least let TCP reconstruct it as a single packet) for each frame buffer. 我正在尝试为每个帧缓冲区发送一个数据包(或至少让TCP将其重构为单个数据包)。 The frame buffer is getting splitted into multiple small packets on the receiving end. 帧缓冲区在接收端被拆分为多个小数据包。

The Java code is the following: Java代码如下:

OutputStream os = clientSocket.getOutputStream();
FileInputStream fos = new FileInputStream("fb");
while (true) {
    int nb = fos.read(buff);
    if (nb <= 0)
        break;
    os.write(buff, 0, nb);
}
fos.close();
os.close();

On the client side, I am trying to read the same amount. 在客户端,我试图读取相同的金额。 nb and size are the same value here: nb和size在这里是相同的值:

n = read(sockfd, buffer, size);
while (n > 0) {
    // We have a new frame
    fprintf(stderr, "New frame: %d\n", n);

    n = read(sockfd, buffer, size);
}

The value of n that is printed is much smaller than size. 打印的n的值比大小小得多。 It receives a lot of packets when I would hope the return from read() would be a packet of the size 'size' (or nb). 当我希望read()的返回将是大小为“ size”(或nb)的数据包时,它将收到很多数据包。

Does anyone please know why is that please? 有谁能知道为什么吗?

Thank you very much for your help! 非常感谢您的帮助!

You don't have control over TCP frame sizes. 您无法控制TCP帧大小。 Network devices can and do fragment packets so that you will receive more packets than you sent. 网络设备可以并且可以对数据包进行分段,以便您收到的数据包比发送的数据包还要多。

The word "stream" is used for a very good reason. 使用“流”一词是有很好的理由的。 You are getting a stream of bytes but there is no framing unless the sender and receiver application impose framing on the stream by including frame markers in the data. 您正在获得字节流,但是没有成帧,除非发送方和接收方应用程序通过在数据中包括帧标记将流强加到帧上。 One common way used by a lot of TCP protocols is to use \\r\\n as a frame marker. 许多TCP协议使用的一种常见方式是使用\\r\\n作为帧标记。 This means that the receiver collects incoming data but does not process it until it encounters a frame marker. 这意味着接收器收集传入的数据,但直到遇到帧标记时才对其进行处理。 At that point, the receiver processes one frame and then goes on looking for the next frame marker. 此时,接收器处理一帧,然后继续寻找下一个帧标记。

One thing that you should consider is using a cross-platform cross-language library like ZeroMQ to handle framing for you. 您应该考虑的一件事是使用像ZeroMQ这样的跨平台跨语言库来为您处理帧。

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

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