【问题标题】:String length through TCP通过 TCP 的字符串长度
【发布时间】:2014-01-17 04:33:18
【问题描述】:

我正在尝试发送一个随机生成的 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;
} 

【问题讨论】:

  • 没有。它发送缓冲区中的内容,直到您指定的长度。

标签: c


【解决方案1】:

而不是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

【讨论】:

    【解决方案2】:

    1 您应该将要发送的内容转换成 Big-Endian

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      相关资源
      最近更新 更多