2013-07-21 60 views
0

我正在C++上创建一个简单的客户端/服务器多人游戏。所以客户端连接成功,并且当我试图发送时。它,我从调试此消息 “信号接收:SIGPIPE(碎管)” 下面是代码:收到的信号:SIGPIPE(破碎的管道)

服务器:

string _ip = "127.0.0.1"; 
    sockaddr_in _tempFullAddress; 
    int _templistener; 
    int _tempPort; 
    int mes = 27; 

    _tempFullAddress.sin_family = AF_INET; 
    _tempFullAddress.sin_port = 5326; 
    inet_aton(_ip.c_str(), &(_tempFullAddress.sin_addr)); 

    _templistener = socket(AF_INET, SOCK_STREAM, 0); 

    int bindResult = 
bind(_templistener, (sockaddr*) &_tempFullAddress, sizeof(_tempFullAddress)); 
    if (bindResult<0){ 
     cout<<"Error on binding\n"; 
     return 0; 
    } 

    listen(_templistener, 1); 

    char buf[1]; 
    buf[0]=(char)mes; 

    accept(_templistener, NULL, NULL); 
    send(_templistener, buf, 1, 0); 

    close(_templistener); 

客户:

sockaddr_in _tempServerAddress; 
    int _tempServerPort=5326; 
    int _tempSocket; 
    char buf[1]; 
    string _serverIp=""127.0.0.1"; 

    _tempServerAddress.sin_family=AF_INET; 
    _tempServerAddress.sin_port=_tempServerPort; 
    inet_aton(_serverIp.c_str(), &(_tempServerAddress.sin_addr)); 
    _tempSocket=socket(AF_INET, SOCK_STREAM, 0); 

    connect(_tempSocket, (sockaddr*)&_tempServerAddress, sizeof(_tempServerAddress)); 

    recv(_tempSocket, buf, 1, 0); 
    _serverPort=5300+((int)buf[0]-'0'); 

客户端成功连接,但没有收到任何东西。

回答

1

您无法在侦听套接字上发送数据。 accept返回一个表示连接的新套接字,并在该连接上发送数据。

int _tempconn = accept(_templistener, NULL, NULL); 
send(_tempconn, buf, 1, 0); 

close(_tempconn); 
close(_templistener); 
+0

谢谢,它的工作原理! – leoUA