erlang websocket 练习

周末有空试了一下websocket 下面是我的代码
chat.erl

-module(chat).
-compile(export_all).

start() ->
	case gen_tcp:listen(8080,[binary, {packet, 0}, {active, true}, {reuseaddr, true}, {packet_size,1024*2},{keepalive,true}]) of
        {ok, Listen} -> 
            spawn(fun() -> par_connect(Listen) end);
        _Err -> 
            io:format("Accept connections failed:~w~n",[_Err])          
    end.

par_connect(Listen) ->
   {ok, Socket} = gen_tcp:accept(Listen),
   spawn(fun() -> par_connect(Listen) end),
   wait(Socket).

wait(Socket) ->
   receive
       {tcp, Socket, Bin} ->
		   io:format("received:~ts~n",[binary_to_list(Bin)]),
           gen_tcp:send(Socket, websockets:handshake(Bin)),
           loop(Socket);
       Any ->
           io:format("Received:~p~n",[Any]),
           wait(Socket)
   end.

loop(Socket) ->
   receive
       {tcp, Socket, Data} ->		  
           io:format("received:~ts~n",[binary_to_list(Data)]),
		   gen_tcp:send(Socket, [Data]),
           loop(Socket);
       Any ->
           io:format("Received:~p~n",[Any]),		   
           loop(Socket)
   end.



websockets.erl  负责连接验证应答处理 是网上找的

注意:目前只有 google chrome支持websocket

你可能感兴趣的:(erlang,socket,chrome,Google)