/erlang_websocket

WebSocket Server and Client implementation in Erlang/Mochiweb

Primary LanguageErlang

Erlang WebSocket Server and Client

WebSocket Server

The server is a simple wrapper around the mochiweb_socket_server to allow WebSocket connections. With this wrapper, you can write WebSocket connection loops just like you’d write a normal mochiweb application. Here’s an example (included with the source code):

 
-module(basic_websocket).

-export([start/1, stop/0, loop/1]).

start(Options) ->
    Loop = fun (WebSocket) ->
                   ?MODULE:loop(WebSocket)
           end,
    mochiweb_websocket:start([{name, ?MODULE}, {loop, Loop} | Options]).

stop() ->
    mochiweb_websocket:stop(?MODULE).


loop(WebSocket) ->
    %% Get the data sent from the client
    Data = WebSocket:get_data(),
    
    %% For this example...
    %% Of course you could handle JSON or another format of your choice
    case Data of
	%% On initial connect we get this message
	"client-connected" ->
	    WebSocket:send("You are connected!");
	%% Other messages go here
	Other ->
	    Msg = "You Said: " ++ Other,
	    WebSocket:send(Msg)
    end.
 

WebSocket Client

This is a pure Erlang WebSocket client you can use to call a WebSocket Server from Erlang code. For simplicity, the code defines an Erlang Behaviour you implement for your client. The Behaviour defines the functions outlined in the WebSocket API spec. Here’s an example of a simple client:

 

-module(sample).
-behaviour(websocket_client).
-export([start/0]).
%% websocket specific callbacks
-export([onmessage/1,onopen/0,onclose/0,close/0,send/1]).

send(Data) ->
    websocket_client:write(Data).

start() ->
    websocket_client:start("localhost",8002,?MODULE).

%% Handle incoming messages here
onmessage(Data) ->
    io:format("Got some data:: ~p~n",[Data]).

onclose() ->
    io:format("Connection closed~n").

onopen() ->
    io:format("Connection open~n"),
    send("client-connected").

close() ->
    websocket_client:close().

 

Here’s an example of using the client from an erl shell:

 
> sample:start().
> sample:send("Hello there").
> sample:close().
 

Check out the examples directory.

Requirements:

  1. Erlang 12.5 or greater
  2. Google Chrome Browser developer channel release 4.0.249.0

Getting Started:

  1. download the code
  2. CD into the erlang_websocket directory
  3. run make

Run the example:

  1. CD into the examples/basic directory
  2. run the ‘start.sh’ script
  3. Point the Chrome Browser to ‘http://localhost:8000’