2012-11-22 32 views
0

我想用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上有任何進程。

+0

重新端口80,你有Apache或另一臺Web服務器已經在該端口上監聽? – ultranaut

+0

不,我沒有任何服務器或使用該端口的進程。有任何想法嗎? – yunhasnawa

+4

你需要是root用戶才能綁定到<1024端口。 – whamma

回答

2

您需要終止HTTP響應標頭\r\n\r\n,而不僅僅是\r\n。它也應該從HTTP/1.1 200 OK\r\n開始,沒有領先的\r\n

對於您的端口問題,如果您沒有其他端口正在運行,您可能會發現上次運行的程序創建的套接字仍然存在。要解決此問題,您可以使用setsockopt在套接字上設置SO_REUSEADDR標誌。 (這是不推薦用於一般用途,我相信,因爲您可能會收到不適合你的程序的數據,但對於發展這是非常方便的。)

+0

我的程序從不使用端口80,因爲我不知道如何使用端口80.另外,沒有其他應用綁定到此端口。我相信端口問題是因爲特權問題。但是,有關HTTP響應頭的答案是正確的。謝謝。 – yunhasnawa

3

你的要求與\r\n啓動時它不應該也沒有詳細介紹一狀態代碼,並且在所有標題後需要空行。

char message[] = "HTTP/1.1 200 Okay\r\nContent-Type: text/html; charset=ISO-8859-4 \r\n\r\n<h1>Hello, client! Welcome to the Virtual Machine Web..</h1>"; 

至於你的端口80的問題,其他一些應用程序可能會綁定到它。

0

你需要添加「內容長度:」,長度爲你的HTML代碼,就像這樣:

char msg[] = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-length: 20\r\n\r\n<h1>Hello World</h1>";