0

如何通过套接字接收 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;
}
4

1 回答 1

7

成功后accept,它会返回一个新连接的套接字,您应该使用它来读取数据。现在您正在丢弃它的返回值,除了检查INVALID_SOCKET. 正如预期的那样,recv不适用于portListener: portListenernever 连接本身。

于 2013-01-17T20:00:59.943 回答