我正在尝试使用C ++创建一个简单的http服务器。我在C ++中遵循beej's guide网络编程。
当我在某个端口(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
Hello, client! Welcome to the Virtual Machine Web..
";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;
问题是,即使我在响应字符串的早期添加了标题,为什么浏览器没有正确显示HTML而只显示纯文本?它显示了这样的事情:
Content-Type: text/html; charset=ISO-8859-4
Hello, client! Welcome to the Virtual Machine Web..
不是一个很大的“Hello,client!..”字符串,就像通常用h1标记的字符串一样。问题是什么?我在标题中遗漏了什么吗?
另一个问题是,为什么服务器不能在端口80中运行?服务器中的错误日志说:
server: bind: Permission denied
server: bind: Permission denied
Server failed to bind
libc++abi.dylib: terminate called throwing an exception
请帮忙。谢谢。编辑:我在端口80上没有任何进程。