0
当我使用套接字时,程序服务器进程没有收到来自客户端进程/类的任何消息。 给用户的输入端口是5555,但是当程序退出客户端的构造函数时,sin的端口号不匹配(我认为这是因为htons),同样也是ip地址。 请帮我解决这个问题。我的程序不发送消息或没有收到套接字,ip是127.0.0.1
这是我的服务器代码:
#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'](https://www.freebsd.org/cgi/man.cgi?query=bind&sektion=2)。 – user4581301
@ user4581301 UDP没有'listen'。 –