字符串长度通过TCP

时间:2014-01-17 04:33:18

标签: c

我正在尝试发送一个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;
} 

2 个答案:

答案 0 :(得分:2)

而不是

中的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定义为。

答案 1 :(得分:0)

1您应该转换要在Big-Endian中发送的内容

2。它不会,服务器收到客户端发送的内容