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