问题描述
我引认为的write()
只能发送一个字节的数据缓冲区(即符号字符),所以我怎么发送使用长整数数组的C 的write()
在sys / socket.h中库函数?
很明显,我不能只投或转换长为char,因为超过127的任何数字将是畸形的。
我看了看这个问题,how分解整数数组为一个字节数组(像素的编码),但不明白吗? - 请会有人哑下来一点点,如果这就是我要找的。 P>
跟进的问题:
Why执行从TCP套接字读取一个整数数组时,我会有奇怪的结果?
原型写的是:
ssize_t供写入(INT FD,常量无效* buf中,为size_t计数);
所以当它以字节为单位的联信写道,它可以接受任何类型的指针。传递一个为int *
将是一点问题都没有。
编辑:
我想不过,建议更换,你也送你打算先发送所以reciever知道多少阅读整数数量。事情是这样的(检查不再赘述错误):
INT X [10] = {...};
诠释计数= 10;
写(袜子,和放大器;算,的sizeof(计数));
写(袜子中,x,的sizeof(X));
请注意:如果数组是动态内存(如你的malloc
ED),你不能使用的sizeof
在上面。在这种情况下计数应该等于:的sizeof(int)的* element_count
编辑:
作为Brian米切尔指出的,你可能会需要小心的的问题,以及。发送任何多字节值时(如在我推荐的计数以及阵列的每个元素)是这种情况。这是与完成的: htons
/ htonl
和 ntohs和
/ ntohl
功能。
I'm lead to believe that write()
can only send data buffers of byte (i.e. signed char), so how do I send an array of long integers using the C write()
function in the sys/socket.h library?
Obviously I can't just cast or convert long to char, as any numbers over 127 would be malformed.
I took a look at the question, how to decompose integer array to a byte array (pixel codings), but couldn't understand it - please could someone dumb it down a little if this is what I'm looking for?
Follow up question:
Why do I get weird results when reading an array of integers from a TCP socket?
the prototype for write is:
ssize_t write(int fd, const void *buf, size_t count);
so while it writes in unites of bytes, it can take a pointer of any type. Passing an int*
will be no problem at all.
EDIT:
I would however, recomend that you also send the amount of integers you plan to send first so the reciever knows how much to read. Something like this (error checking omitted for brevity):
int x[10] = { ... };
int count = 10;
write(sock, &count, sizeof(count));
write(sock, x, sizeof(x));
NOTE: if the array is from dynamic memory (like you malloc
ed it), you cannot use sizeof
on it. In this case count would be equal to: sizeof(int) * element_count
EDIT:
As Brian Mitchell noted, you will likely need to be careful of endian issues as well. This is the case when sending any multibyte value (as in the count I recommended as well as each element of the array). This is done with the: htons
/htonl
and ntohs
/ntohl
functions.
这篇关于我如何用C发送整数数组通过TCP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!