[英]My program doesn't send message or doesn't receive to socket, the ip is 127.0.0.1
當我使用套接字時,程序服務器進程不會從客戶端進程/類收到任何消息。 用戶的輸入端口是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()
調用,以及在其中處理請求的無限循環。 也許您是無意間省略了服務器代碼?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.