我正在尝试用 C++ 制作一个简单的 http 服务器。我关注了 beej's guide C++网络编程。
当我在某个端口(8080、2127 等)上运行服务器时,当它通过地址栏访问时成功向浏览器 (Firefox) 发送响应:localhost:PORT_NUMBER,端口 80 除外。
这是我写的代码:
printf("Server: Got connection from %s\n", this->client_ip);
if(!fork()) // This is the child process, fork() -> Copy and run process
{
close(this->server_socket); // Child doesn't need listener socket
// Try to send message to client
char message[] = "\r\nHTTP/1.1 \r\nContent-Type: text/html; charset=ISO-8859-4 \r\n<h1>Hello, client! Welcome to the Virtual Machine Web..</h1>";
int length = strlen(message); // Plus 1 for null terminator
int send_res = send(this->connection, message, length, 0); // Flag = 0
if(send_res == -1)
{
perror("send");
}
close(this->connection);
exit(0);
}
close(this->connection); // Parent doesn't need this;
问题是,即使我很早就在响应字符串中添加了 header ,为什么浏览器没有正确显示 HTML 而只显示纯文本?它显示如下内容:
Content-Type: text/html; charset=ISO-8859-4
<h1>Hello, client! Welcome to the Virtual Machine Web..</h1>
不是像通常带有 h1 标记的字符串那样的大字符串“Hello, client!..”。问题是什么?我在标题中遗漏了什么吗?
另一个问题是,为什么服务器不会在端口 80 上运行?服务器中的错误日志说:
server: bind: Permission denied
server: bind: Permission denied
Server failed to bind
libc++abi.dylib: terminate called throwing an exception
请帮忙。谢谢。编辑:我在端口 80 上没有任何进程。
最佳答案
您需要使用 \r\n\r\n
来终止 HTTP 响应 header ,而不仅仅是 \r\n
。它还应该以更像 HTTP/1.1 200 OK\r\n
的内容开头,没有前导 \r\n
。
对于你的端口问题,如果你没有在有问题的端口上运行任何其他东西,你可能会发现上次运行程序创建的套接字仍然存在。要解决此问题,您可以使用 setsockopt
在套接字上设置 SO_REUSEADDR
标志。 (不建议将其用于一般用途,我相信是因为您可能会收到并非为您的程序准备的数据,但对于开发而言它非常方便。)
关于c++ - 使用 C++ Socket API 通过套接字连接将 HTML 标记发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13504590/