我尝试通过 UDP 将数据从一台计算机发送到另一台计算机(第一台计算机:Ubuntu,C++ with Eclipse,第二台计算机 Windows 10 Matlab 2014b)。C++ 计算机应该作为服务器工作。将数据从 C++ 发送到 Matlab 工作正常,但我无法以相反的方向发送数据。每次我的 C++ 程序到达 recvfrom() 时,它都会在此时空闲,不再做任何事情,即使 matlab 一遍又一遍地发送数据。我尝试通过 netcat 在 ubuntu 上接收数据,同时使用 Matlab 发送包,效果也很好。即使我用 select() 尝试了一些东西,但这只会导致程序到达 select() 时等待 10 秒,然后再次在 recvfrom 处冻结。如果有人可以给我一些帮助,我将不胜感激。
int Socket=socket(AF_INET, SOCK_DGRAM,0);
/*FD_ZERO(&SockSet);
FD_SET(Socket,&SockSet);
sTimeval.tv_sec=0.1;
sTimeval.tv_usec=0;
int status=select(Socket+1,&SockSet,(fd_set*)NULL,(fd_set *)NULL,&sTimeval);
cout<<status<<endl;*/
if(Socket!=-1)
cout<<"Socket created"<<endl;
else
cout<<"Socket not created"<<endl;
unsigned short port=4012;
struct in_addr serverIP;
//(void)inet_pton(AF_INET,"192.168.56.100", &clientIP);
(void)inet_pton(AF_INET,"192.168.56.101", &serverIP);
struct sockaddr_in server;
memset(&server,0, sizeof(server));
server.sin_family=AF_INET;
server.sin_addr=serverIP;
server.sin_port=htons(port);
if(bind(Socket,(struct sockaddr*)&server, sizeof(&server))!=1)
cout<<"Binding successful"<<endl;
else
cout<<"Binding failed";
struct sockaddr client;
memset(&client, 0, sizeof(client));
socklen_t clientlen=0;
struct sockaddr_in* client_in;
memset(&client_in,0,sizeof(client_in));
cout<<"warten vor recv"<<endl;
ssize_t bytesread=recvfrom(Socket, &msg, sizeof(msg), 0, &client,&clientlen);
cout<<(int)bytesread<<endl;
cout<<msg<<endl;
client_in=(struct sockaddr_in*)&client;
char* client_adr=inet_ntoa(client_in->sin_addr);
printf("%s Port%d\n", client_adr, ntohs(client_in->sin_port));
if (bytesread == -1) {
cerr << "Fehler beim empfangen" << endl;
int status = close(Socket);
if (status == 0)
cout << "Socket closed" << endl;
else if (status == -1)
cout << "Socket not closed" << endl;
return (1);
}
//Wenn Infos ueber Client nicht schon vorher aus recvfrom()
/*struct in_addr clientIP;
(void)inet_pton(AF_INET,"192.168.2.102", &clientIP);
struct sockaddr_in client;
memset(&client,0, sizeof(client));
client.sin_family=AF_INET;
client.sin_addr=clientIP;
client.sin_port=htons(portwindows);*/
char msg2[]="12345";
ssize_t bytessent=sendto(Socket,msg2,strlen(msg2),0,(struct sockaddr*)&client,sizeof(client));
cout<<(int)bytessent<< " bytes were sent"<<endl;
int status=close(Socket);
if(status==0)
cout<<"Socket closed"<<endl;
else if(status==-1)
cout<<"Socket not closed"<<endl;