C++ で単純な http サーバーを作成しようとしています。C++ でのネットワーク プログラミングに関する beej のガイドに従いました。
いくつかのポート (8080、2127 など) でサーバーを実行すると、ポート 80 を除く localhost:PORT_NUMBER を使用してアドレス バーからアクセスすると、ブラウザー (Firefox) に応答が正常に送信されます。
これは私が書いたコードです:
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!..」文字列ではありません。何が問題ですか?ヘッダーに何か不足していますか?
もう 1 つの質問は、サーバーがポート 80 で実行されないのはなぜですか? サーバーのエラーログには次のように記載されています。
server: bind: Permission denied
server: bind: Permission denied
Server failed to bind
libc++abi.dylib: terminate called throwing an exception
助けてください。ありがとうございました。編集: ポート 80 にはプロセスがありません。