我想用C++製作一個簡單的http服務器。我遵循C++中網絡編程的beej's guide。通過與C++套接字API的套接字連接向瀏覽器發送HTML標記
當我運行的服務器在某些端口(8080,2127,等等),它成功地發送響應瀏覽器(Firefox),當它通過使用地址欄訪問:本地主機:端口號,除非端口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;
問題是,即使我已經添加了頭很早就響應字符串的,爲什麼瀏覽器不顯示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上有任何進程。
重新端口80,你有Apache或另一臺Web服務器已經在該端口上監聽? – ultranaut
不,我沒有任何服務器或使用該端口的進程。有任何想法嗎? – yunhasnawa
你需要是root用戶才能綁定到<1024端口。 – whamma