如何通过套接字发送 int

How to send int over the socket?

本文关键字:int 套接字 何通过      更新时间:2023-10-16

我正在学习非常基本的套接字编程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. 您没有检查来自任一调用的返回值。 套接字臭名昭著(本质上(容易出错。

  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 receivedn");
        // probably a good idea to close socket
        break;
    }
    else if (result < 0) {
        printf("ERROR!n");
        // probably a good idea to close socket
        break;
    }
}

对于 UDP 套接字,一些主体在错误检查方面保持不变,强制转换为内存缓冲区/从内存缓冲区转换。 但是对于UDP,你不应该做"循环"的事情,因为UDP是一个数据报协议。