我发现SockJS-Erlang 库运行良好。最重要的是,如果 websocket 不可用,它支持后备传输。它使用Cowboy(虽然是旧版本)作为底层服务器,这很好,因为它易于集成。 This escript 和 this HTML page 会给你一个可以玩的工作演示。
这是一个带注释的例子:
start_link(_) ->
application:start(sockjs),
application:start(cowboy),
% generate a SockJS handler
SockjsState = sockjs_handler:init_state(
<<"/browser_socket">>, fun handle_client/3, state, []),
% build the dispatch routes for Cowboy integrating the SockJS handler
Routes = [{'_', [{[<<"echo">>, '...'],
sockjs_cowboy_handler, SockjsState}]}],
% start the cowboy server
cowboy:start_listener(http, 100,
cowboy_tcp_transport, [{port, 8081}],
cowboy_http_protocol, [{dispatch, Routes}]),
% called when a new client connects
handle_client(Conn, init, state) -> {ok, state};
% called when data is received
handle_client(Conn, {recv, Data}, state) ->
% reply to client
Conn:send(Data);
% called when connection is closed
handle_client(_Conn, closed, state) -> {ok, state}.
我对 Apache 的建议是使用 HAProxy 进行 WebSocket 连接,使用 Apache 提供 Javascript 和 PHP。