繁体   English   中英

如何通过套接字发送 int?

[英]How to send int over the socket?

我正在使用 C++ 学习非常基本的套接字编程,我被困在试图通过套接字发送随机生成的 int 的部分。

服务器.cpp

int code = rand();
send(connfd, (char*)code, sizeof(int), 0);

客户端.cpp

int code = 0;
recv(connfd, (char*)code, sizeof(int), 0);

我究竟做错了什么?

对于初学者:

  1. 您没有检查任何一个调用的返回值。 sockets 是臭名昭著的(本质上)容易出错。

  2. 假设所有字节都将一起发送和接收 - 但 TCP 容易出现分段、碎片、部分发送和各种你不应该假设你会在一次调用中收到所有发送的东西。 这使得检查返回值变得更加重要!

  3. 你做的那个演员: (char*)code不正确。 更适合做(char*)&code ,但它不识别部分接收。

假设您使用的是 TCP 套接字:

发送:

int data = rand();
char* tosend = (char*)&data;
int remaining = sizeof(data);
int result = 0;
int sent = 0;
while (remaining > 0) {
    result = send(connfd, tosend+sent, remaining, 0);
    if (result > 0) {
        remaining -= result;
        sent += result;
    }
    else if (result < 0) {
        printf("ERROR!\n");
        // probably a good idea to close socket
        break;
    }
}

收到:

int value = 0;
char* recv_buffer = (char*)&value;
int remaining = sizeof(int);
int received = 0
int result = 0;
while (remaining > 0) {
    result = recv(connfd, recv_buffer+received, remaining, 0);
    if (result > 0) {
        remaining -= result;
        received += result;
    }
    else if (result == 0) {
        printf("Remote side closed his end of the connection before all data was received\n");
        // probably a good idea to close socket
        break;
    }
    else if (result < 0) {
        printf("ERROR!\n");
        // probably a good idea to close socket
        break;
    }
}

对于 UDP 套接字,一些原则在错误检查、投射到/从 memory 缓冲区方面保持不变。 但是对于 UDP 你不应该做“循环”的事情,因为 UDP 是一个数据报协议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM