发送和接收 int C++

Send and receive int C++

本文关键字:int C++      更新时间:2023-10-16

如何int发送到服务器 4 字节,并在服务器端将此缓冲区转换为 int。

客户端:

void send_my_id()
{
 int my_id = 1233;
 char data_to_send[4];
 // how to convert my_id to data_send?
 send(sock, (const char*)data_to_send, 4, 0);
}

服务器端:

void receive_id()
{
 int client_id;
 char buffer[4];
 recv(client_sock, buffer, 4, 0);
 // how to conver buffer to client_id? it must be 1233;
}

您可以简单地将int的地址转换为char*并将其传递给send/recv。请注意使用 htonlntohl 来处理字节序。

void send_my_id()
{
 int my_id = 1233;
 int my_net_id = htonl(my_id);
 send(sock, (const char*)&my_net_id, 4, 0);
}
void receive_id()
{
 int my_net_id;
 int client_id;
 recv(client_sock, &my_net_id, 4, 0);
 client_id = ntohl(my_net_id);
}

注意:我保留了缺乏结果检查。实际上,您需要额外的代码来确保发送和接收传输所有必需的字节。

自互联网开始以来,通常的惯例是按网络字节顺序发送二进制整数(读取大端序)。您可以使用htonl(3)和朋友来做到这一点。

在发送端:

int my_id = 1233;
char data_to_send[4];
memcpy(&data_to_send, &my_id, sizeof(my_id));
send(sock, (const char*)data_to_send, 4, 0);

在接收方:

int client_id;
char buffer[4];
recv(client_sock, buffer, 4, 0);
memcpy(&my_id, &buffer, sizeof(my_id));

注意:两边的int大小和字节序必须相同。

C++

int receive_int_from_socket(int socket_id){
    int network_value;
    int value;
    int bytes_received = recv(socket_id, &network_value, 4, 0);
    if(bytes_received > 0){
        cout << "num of bytes received: " << bytes_received << endl;
        cout << "integer form received: " << ntohl(network_value) << endl;
        return ntohl(network_value);
    }
    return -1;
}
int send_int_over_socket(int socket_id, int value){
    cout << "sent number:" << value << endl;
    int network_value = htonl(value);
    int bytes_sent = send(socket_id, (const char*)&network_value, 4, 0);
    cout << "sent " << bytes_sent << " bytes" << endl;
    return bytes_sent > 0 ? bytes_sent : -1;
}