利用Socket或TcpClient/TcpListener,编写一个HTTP服务器c++
时间: 2024-02-19 14:02:32 浏览: 131
好的,我可以为您提供一个简单的示例,使用C++语言利用Socket实现一个HTTP服务器:
```c++
#include <iostream>
#include <string>
#include <WS2tcpip.h>
#pragma comment (lib, "ws2_32.lib")
int main()
{
// 初始化Winsock
WSADATA data;
WORD version = MAKEWORD(2, 2);
int wsOk = WSAStartup(version, &data);
if (wsOk != 0)
{
std::cerr << "Can't initialize Winsock! Quitting" << std::endl;
return 1;
}
// 创建Socket
SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == INVALID_SOCKET)
{
std::cerr << "Can't create a socket! Quitting" << std::endl;
return 1;
}
// 绑定Socket到IP地址和端口
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(8080);
hint.sin_addr.S_un.S_addr = INADDR_ANY;
bind(listening, (sockaddr*)&hint, sizeof(hint));
// 告诉Winsock这是一个监听Socket
listen(listening, SOMAXCONN);
// 等待连接
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);
char host[NI_MAXHOST]; // 远程名称
char service[NI_MAXSERV]; // 远程端口
ZeroMemory(host, NI_MAXHOST); // 确保缓存区为空
ZeroMemory(service, NI_MAXSERV);
if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
{
std::cout << host << " connected on port " << service << std::endl;
}
else
{
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
std::cout << host << " connected on port " << ntohs(client.sin_port) << std::endl;
}
// 关闭监听Socket
closesocket(listening);
// 循环接收和发送数据
char buf[4096];
while (true)
{
ZeroMemory(buf, 4096);
// 等待客户端发送数据
int bytesReceived = recv(clientSocket, buf, 4096, 0);
if (bytesReceived == SOCKET_ERROR)
{
std::cerr << "Error in recv(). Quitting" << std::endl;
break;
}
if (bytesReceived == 0)
{
std::cout << "Client disconnected" << std::endl;
break;
}
// 处理请求
std::string response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\nHello world!";
send(clientSocket, response.c_str(), response.size() + 1, 0);
}
// 关闭Socket
closesocket(clientSocket);
// 清理Winsock
WSACleanup();
return 0;
}
```
这是一个简单的HTTP服务器示例,它监听在本地8080端口,收到请求后会返回“Hello world!”。您可以根据自己的需求进行修改和扩展。
阅读全文