使用C++获取HTTP get参数

getting HTTP get argument using C++

本文关键字:get 参数 HTTP 获取 C++ 使用      更新时间:2023-12-28

我想从运行javascript的程序向C++程序发送一些消息。在发送方程序(javascript)中,我使用了这个:

xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://localhost:55555/?msg=" + message, false );
xmlHttp.send( null );

在接收器程序(C++)中我使用了这个:

printf("'nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
    printf("Failed. Error Code : %d",WSAGetLastError());
    return 1;
}
printf("Initialised.'n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
    printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.'n");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 55555 );
//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
    printf("Bind failed with error code : %d" , WSAGetLastError());
    exit(EXIT_FAILURE);
}
puts("Bind done");

现在我想获取http参数(登录url后的消息),但我不知道怎么做。请帮帮我。。。

您实际上想要实现的是创建一个HTTP服务器。到目前为止,您编写的代码只创建了一个TCP套接字并绑定到本地端口5555。您仍然希望让套接字侦听、接受请求,然后读取客户端发送的数据。

然而,这只是你想要实现的一小部分。您的javascript实际上正在形成一个HTTP请求(应用层),而您的服务器正在传输层(TCP)侦听传入数据。所以,它对HTTP协议一无所知。因此,您必须编写逻辑来解析在TCP层接收到的缓冲区,以将其解码为HTTP。

您可以为所有这些编写代码,也可以使用一些工具包,如wt或apache模块2