发送和接收 int C++
Send and receive int C++
如何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
。请注意使用 htonl
和 ntohl
来处理字节序。
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;
}
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- 长 长 int 不要 长 int 好
- C++程序在循环后给出奇怪的int值
- 如何计算数据类型的范围,例如int
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)