gpt4 book ai didi

c - 通过 TCP 的字符串长度

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:26 25 4
gpt4 key购买 nike

我正在尝试发送随机生成的 160x120 uint32_t 像素值数组。前两个字节必须具有值(160 和 120),并且两个值的数据格式必须为 int32_t。我如何以某种方式将 int32_t 的这两个值插入 uint32_t 数组的 p[0] 和 p[1]?第二个问题是:此代码是否将字符串长度作为数据的第一个字节发送?。在 p[0] 之前?

int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
int c, iResult;
char sendbuf [DEFAULT_BUFLEN];
uint32_t* p;
int32_t* z;
int i;

// Send uint8_t data to client

p = (uint32_t*)sendbuf;

p[0] = 120; // must be an int32_t value
p[1] = 160; // must be an int32_t value

srand (time(NULL));
for (i = 3; i < 19203; i++)
{
p[i] = rand() % 4294967295; //range 0-4294967294 */
printf("%d\n", p[i]);
}
iResult = send(client_socket, sendbuf, (int32_t)strlen(sendbuf), 0);
return 0;

if (iResult == SOCKET_ERROR)
{
printf("Send failed. Error Code : %d\n", WSAGetLastError());
iResult = 1;
}
else
{
printf("Bytes Sent: %d\n", iResult);
iResult = 0;
}

// shutdown the connection since no more data will be sent
if (shutdown(client_socket, SD_SEND) == SOCKET_ERROR)
{
printf("Shutdown failed. Error Code : %d\n", WSAGetLastError());
iResult = 1;
}

closesocket(client_socket);
WSACleanup();

return iResult;
}

最佳答案

代替 strlen(sendbuf)

iResult = send(client_socket, sendbuf, (int32_t)strlen(sendbuf), 0);

适当计算大小

//         number of pixels + int size + 2 ints for p[0] and p[1]
int size = 160*120*sizeof(uint32_t) + 2 *sizeof(uint32_t);
iResult = send(client_socket, sendbuf, size, 0);

还要确保 DEFAULT_BUFLEN 大于 size。如果你愿意,你可以定义DEFAULT_BUFLEN

关于c - 通过 TCP 的字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21177972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com