【问题标题】:Receive GET request through sockets通过套接字接收 GET 请求
【发布时间】:2013-01-17 19:54:30
【问题描述】:

如何通过套接字接收 GET 请求?例如我在浏览器中写:

127.0.0.1:41233/?data=mymessage

我希望我的应用程序接收“mymessage”。我写了这段代码,但 recv() 返回 WSAENOTCONN 错误,我不知道如何修复它。

int main() {
    WSADATA socketData;
    SOCKET portListener;
    struct sockaddr_in saInfo = {0};
    if ( WSAStartup( MAKEWORD(1, 1), &socketData ) != 0) {
        printf( "WSAStartup() error!" );
        return 0;
    }
    portListener = socket( AF_INET, SOCK_STREAM, 0 );
    if ( portListener == INVALID_SOCKET ) {
        printf( "socket() error!" );
    } 
    else {
        saInfo.sin_family = AF_INET;
        saInfo.sin_port = htons(41233);
        saInfo.sin_addr.S_un.S_addr = inet_addr( "127.0.0.1" );
        if ( bind( portListener, ( sockaddr * ) &saInfo, sizeof(saInfo)) == SOCKET_ERROR ) {
            printf( "bind() error!\n" );
            closesocket( portListener );
            return 0;
        }
        if ( listen( portListener, SOMAXCONN ) == SOCKET_ERROR ) {
            printf( "listen() error!\n" );
            closesocket( portListener );
            return 0;
        }
        if ( accept( portListener, NULL, NULL ) == INVALID_SOCKET ) {
            printf( "accept() error!\n" );
            closesocket( portListener );
            return 0;
        }
        char buf[128];
        int rcvCount;
        rcvCount = recv( portListener, buf, 128, 0 );
        printf( "Error: %d\n", WSAGetLastError() );
        if ( rcvCount > 0 ) {
            printf( "%s\n", buf );
        }
        closesocket( portListener );
    }
    WSACleanup();
    return 0;
}

【问题讨论】:

    标签: c++ windows sockets windows-7


    【解决方案1】:

    accept 成功时,它会返回一个新的已连接 套接字,您应该使用它来读取数据。现在你要丢弃它的返回值,除了检查INVALID_SOCKET。正如预期的那样,recv 不适用于 portListenerportListener 永远不会自行连接。

    【讨论】:

      猜你喜欢
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      相关资源
      最近更新 更多