当我使用套接字时,程序服务器进程没有收到来自客户端进程/类的任何消息。 用户的输入端口是5555,但是当程序退出客户端的构造函数时,sin的端口号不匹配(我认为是因为htons),ip地址也是如此。 请帮我解决这个问题。
这是我的服务器代码:
#include "SocketUDP.h"
/*
* class constructor
*/
SocketUDP::SocketUDP() {
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
perror("error creating socket");
}
/*
* class destructor
*/
SocketUDP::~SocketUDP() {
close(sock);
}
/*
* this function recieves a message from client/server
* @param - the length of the message
*/
std::string SocketUDP::RecieveMessage(){
unsigned int from_len = sizeof(struct sockaddr_in);
char buffer[4096];
memset(&buffer, 0, sizeof(buffer));
int bytes = recvfrom(sock, buffer, sizeof(buffer), 0,
(struct sockaddr *) &from, &from_len);
if (bytes < 0)
perror("error reading from socket");
return std::string(buffer);
}
这是客户端:
#include "UDPClient.h"
/*
* class constructor
*/
UDPClient::UDPClient(char * ip, int port) {
memset(&sin, 0, sizeof(sin));
sin.sin_addr.s_addr = inet_addr(ip);
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
}
/*
* class destructor
*/
UDPClient::~UDPClient() {
// TODO Auto-generated destructor stub
}
/*
* this function sends a message to the client/server
* @param - the message
*/
int UDPClient::SendMessage(std::string st){
int sent_bytes = sendto(sock, st.c_str(), st.length(), 0,
(struct sockaddr *) &sin, sizeof(sin));
if (sent_bytes < 0)
perror("error writing to socket");
return sent_bytes;
}
最佳答案
您缺少对服务器中 bind()
的调用。这是您告诉操作系统应该在哪个端口 (5555) 上监听传入的 UDP 数据包的地方。
如果在服务器中省略 bind()
会很困惑。在这种情况下,操作系统会选择一个随机端口进行接收,这通常不是人们想要的。
类名 UDPSocket
表示这只是 UDP 套接字的包装器,而不是服务器。服务器还有一个 bind()
调用,以及一个处理请求的无限循环。也许您不小心遗漏了服务器代码?
关于c++ - 我的程序不发送消息或不接收到套接字,ip 是 127.0.0.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34401016/