我试着发送一个160x120uint32像素值的数组,我随机生成。前两个字节必须有值(160和120),两个值的数据格式必须为int32。如何将int32的这两个值以某种方式推送到uint32数组的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;
}

最佳答案

而不是

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);

还要确保strlen(sendbuf)等于大于DEFAULT_BUFLEN。如果需要,可以将size定义为。

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

10-12 02:59