我正在通过TCP从LabVIEW向此C程序发送单帧(160x120)来测试字节顺序。我设法将字节转换为uint32像素值,但问题是循环重复在控制台应用程序中打印接收的数据。这里的要点是,我将打印收到的19200(160x120)uint32值并停止打印该值,以便我可以检查帧的像素值。那可能吗 ?。代码: (我试图在for循环中将“len”更改为“160 * 120”,但我在控制台中得到了一些奇怪的值)。
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET s , new_socket;
struct sockaddr_in server , client;
int c;
int iResult;
int receivedCount = 0;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
typedef unsigned int uint8_t;
unsigned int i;
size_t len;
uint8_t* p;
uint8_t value;
p = (uint8_t*)((void*)recvbuf);
do
{
iResult = recv( new_socket, recvbuf, recvbuflen, 0);
len = iResult/sizeof(uint8_t);
for(i=0; i<len; i++)
{
value = p[i];
printf("%lu\n",value);
}
}
while( iResult > 0 );
closesocket(new_socket);
WSACleanup();
}
答案 0 :(得分:1)
要合并我的评论,以下是我将如何重写您的代码:
int main(int argc, char *argv[]) {
WSADATA wsa;
SOCKET s, new_socket;
struct sockaddr_in server, client;
int c, iResult, receivedCount = 0;
unsigned long totalReceived = 0, totalExpected=160*120;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
typedef unsigned int uint8_t;
uint8_t i, value;
size_t len;
uint8_t* p;
p = (uint8_t*)recvbuf;
do {
iResult = recv(new_socket, recvbuf, recvbuflen, 0);
len = iResult/sizeof(uint8_t);
for (i=0; i<len; i++) {
value = p[i];
totalReceived++;
printf("%lu\n", value);
if (totalReceived >= totalExpected) {
printf("Retrieved expected data\n");
}
}
} while (iResult > 0);
if (totalReceived < totalExpected) {
printf("Received less than expected: %lu < %lu\n", totalReceived, totalExpected);
}
closesocket(new_socket);
WSACleanup();
}
这包括“双重投射”更改,并在多个recv
来电中捕获收到的数据。