[英]TCP-Server sending a file in a packet structure (to a non Java client)
Me asking one of those questions again :P 我再次问这些问题之一:P
Since I'm porting my C++ server to a Java server (and it's nearly done) I'm missing only one thing: 由于我要将C ++服务器移植到Java服务器(这几乎完成了),所以我只缺少一件事:
Sending files. 正在发送文件。
I can't wrap my head around on how to construct the packet in Java to send it via DataOutputStream. 我无法确定如何在Java中构造数据包以通过DataOutputStream发送它。
In C++ I prepared the packet in this way (first 4bytes reserved for the file_size, rest the file itself): 在C ++中,我以这种方式准备了数据包(为file_size保留了前4个字节,其余文件本身保留了):
char *pData = new char[file_size];
memcpy(pData, charArray.data(), file_size);
char *packet = new char[file_size + 4];
memset(packet, 0, file_size + 4);
*(int*)(packet) = file_size;
memcpy((char*)(packet + 4), pData, file_size);
int r = file_size + 4;
sendall(stream, packet, &r);
I hope you can help me out here, I'm able to construct simple packets but this one is giving me a headache :P 希望您能在这里为我提供帮助,我能够构造简单的数据包,但这让我很头疼:P
Do I merge the bytes or how would I accomplish the C++ code in Java x..x 是否合并字节或如何在Java x..x中完成C ++代码
Thanks in advance! 提前致谢!
sendall func: sendall函数:
int sendall(TCPStream *s, char *buf, int *len)
{
int total = 0;
int bytesleft = *len;
int n;
while(total < *len)
{
n = s->send(buf+total, bytesleft);
if (n == -1) break;
total += n;
bytesleft -= n;
}
*len = total;
return n ==-1 ? -1 : 0;
}
The Java equivalent of that C code is: 该C代码的Java等价物是:
int file_size = ...;
byte[] file_data = ...;
byte[] packet = new byte[file_size + 4];
ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN).putInt(file_size);
System.arraycopy(file_data, 0, packet, 4, file_size);
You need to confirm whether the file size was sent with high or low byte first, and change to BIG_ENDIAN
if needed. 您需要确认文件大小是先发送高字节还是低字节,然后根据需要更改为
BIG_ENDIAN
。
Since C code just added file size as int
, and was likely run on Intel processor, the result was LITTLE_ENDIAN
, which is why I specified that in the code above. 由于C代码只是将文件大小添加为
int
,并且很可能在Intel处理器上运行,因此结果是LITTLE_ENDIAN
,这就是为什么我在上面的代码中指定了它。 But as @paulsm4 said , you should test this. 但是正如@ paulsm4 所说 ,您应该测试一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.