使用Erlang實現http server是否更有優勢?
謝邀。用Erlang當然方便了。隨手就給你寫一個出來。
-module(my_http_server).
-export([start/0, accept/1, handle_connection/1]).
start() -&>
{ok, Socket} = gen_tcp:listen(8080, [binary, {packet, http}, {active, false}, {reuseaddr, true}]),
Pid = spawn(?MODULE, accept, [Socket]),
ok = gen_tcp:controlling_process(Socket, Pid),
ok.
accept(Socket) -&>
{ok, Conn} = gen_tcp:accept(Socket),
Pid = spawn(?MODULE, handle_connection, [Conn]),
ok = gen_tcp:controlling_process(Conn, Pid),
?MODULE:accept(Socket).
handle_connection(Socket) -&>
{ok, {http_request, Method, Path, Version}} = gen_tcp:recv(Socket, 0),
Headers = recv_headers(Socket),
ok = inet:setopts(Socket, [{packet, raw}]),
handle_request(Socket, Method, Path, Version, Headers).
recv_headers(Socket) -&>
case gen_tcp:recv(Socket, 0) of
{ok, {http_header, _, Field, _, Value}} -&>
[{Field, Value}|recv_headers(Socket)];
{ok, http_eoh} -&>
[]
end.
handle_request(Socket, "GET", {abs_path, "/"}, {1,1}, _) -&>
ok = gen_tcp:send(
Socket,
[&<&<"HTTP/1.1 200 OK
"&>&>,
&<&<"Connection: close
"&>&>,
&<&<"Content-Type: text-plain
"&>&>,
&<&<"
"&>&>,
&<&<"OK
"&>&>]),
ok = gen_tcp:close(Socket).
不服你可以用C++寫一個啊
顯然不是么,你看Python的版本:
python -m SimpleHTTPServer 8080
如果可以用庫C++也沒多麻煩,比如用我的Fiberized.IO
#include &
#include &
using namespace fibio::http;
int fibio::main(int argc, char *argv[]) {
fibio::this_fiber::get_scheduler().add_worker_thread(3);
return server(8080).handler(
route(
path_("/add/:x/:y")&>&>[](int x, int y){return x+y;}
)
).run().value();
}
哪個不比 @bhuztez 的那個Erlang版本短多了,而且單線程也能飈個幾萬qps的……
沒必要再用erlang寫http server了,用mochiweb或者cowboy,都很棒。但erlang本身適不適合用來寫http server不太好評判
可以熱更新
package main
import "net/http"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
})
http.ListenAndServe(":8081", nil)
}
推薦閱讀:
※為什麼目前web伺服器一般用Linux操作系統而不是windows?
※Node伺服器是如何處理大量請求的?
※鬥魚是怎麼做到十幾萬人超清直播的,帶寬夠嗎?
※docker和virtualenv有什麼區別?
TAG:伺服器 | Erlang編程語言 |