c++ - 收到信号 : SIGPIPE (Broken pipe)

标签 c++ sockets broken-pipe

我正在使用 C++ 创建一个简单的客户端/服务器多人游戏。所以客户端连接成功,当我试图发送 smth 时。对此,我从调试器“收到信号: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');

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

最佳答案

您不能在监听套接字上发送数据。 accept 返回代表连接的新套接字,然后您在该连接上发送数据。

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

close(_tempconn);
close(_templistener);

关于c++ - 收到信号 : SIGPIPE (Broken pipe),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17770014/

相关文章:

c++ - 执行外部程序的简单 C++ 跨平台方式

c - 在 C 中使用套接字处理不同大小的数据包

c# - .NET C# socket 在两个不同的线程上发送

networking - Broken Pipe 和 Connection reset by peer 有什么区别?

c++ - cURL c++ 和 gunzip

c++ - 什么时候用逗号来分隔 C++ 中的两个或多个条件比较合适?

java - HTTURLConnection setFixedLengthStreamingMode 导致 SSL broken pipe 异常

io - 过滤掉断管错误

c++ - std::less<int> 的正确参数类型是什么?

perl - 如何使脚本在IPv6地址上工作