C ++ Socket Prograamming UDP双向通信

时间:2016-02-26 21:37:48

标签: c++ sockets udp

我从sendto()函数得到-1,我不知道为什么。我尝试了很多东西,但似乎什么都没有用? 我可以从客户端获取消息,但我无法将msg从服务器发送到客户端。

char msg[100]="hellloo";
int conn_sock;
struct sockaddr_in server,client;
conn_sock = socket(AF_INET,SOCK_DGRAM,0);

server.sin_family=AF_INET;
server.sin_port = htons(2219);
server.sin_addr.s_addr = inet_addr("127.0.0.1");

socklen_t len = sizeof(server);

bind(conn_sock,(struct sockaddr *)&server,len);



while(strcmp(msg,"QUIT") !=0) 
    {       
        recvfrom(conn_sock,&msg,sizeof(msg),0,(struct sockaddr*)&client,(socklen_t *)&client);
        cout<<"Data received from the Client : "<<msg<<endl;
        //cout<<"Client Address "<<inet_ntoa(client.sin_addr)<<endl;
        //cout<<"Client Port "<<ntohs(server.sin_port)<<endl;   

        memset(msg, 0, sizeof(msg));
        cout<<"Write Msg : ";   
        cin.getline(msg,sizeof(msg));
        socklen_t l = sizeof(&client);
        int n = sendto(conn_sock,&msg,100,0,(struct sockaddr*)&client,l); 
        cout<<n<<endl;          
        //cout<<"Client Address "<<inet_ntoa(client.sin_addr)<<endl;
        //cout<<"Client Port "<<ntohs(server.sin_port)<<endl;   

    }
close(conn_sock);
return 0;

0 个答案:

没有答案