如何通过套接字发送 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);
我做错了什么?
对于初学者:
-
您没有检查来自任一调用的返回值。 套接字臭名昭著(本质上(容易出错。
-
假设所有字节将一起发送和接收 - 但TCP容易出现分段,碎片,部分发送以及各种您永远不应该假设您将在一次调用中收到所有发送的内容。 这使得检查返回值变得更加重要!
-
你做的那个演员:
(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是一个数据报协议。
相关文章:
- 当套接字连接断开时检测C/C++Unix
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- 套接字读取后,我在缓冲区中看到意外输入
- 如何在CPP中创建应该在Windows和Linux上运行的套接字?
- 我可以与 python 服务器而不是 c++ 客户端建立 tcp/ip 套接字吗?
- 套接字连接"Operation not permitted"错误,甚至使用升压/平发器根.cpp
- WINAPI 注册应用程序重新启动时不清除打开的套接字
- (Winsock) UDP 接收工作正常,但同一套接字的发送失败
- 在 UDP 套接字上发送结构、浮点数和 int C++
- 如何通过套接字发送 int
- 通过套接字发送时,字符变为int
- .NET 如何通过套接字 C-Sharp 获取 int
- 如何通过套接字C++服务器/Java客户端发送int
- 在套接字中使用 send() 方法发送 "string" 和"int" var
- 将数据从两种不同的数据结构插入 std::map <std::string, int> mymap 并通过套接字发送
- 在TCP套接字连接上发送int值
- 套接字绑定不会返回 int
- 在C/ c++中通过套接字发送int