web sockets almost working ....

Joe Armstrong erlang@REDACTED
Thu Dec 10 11:21:18 CET 2009


Very exciting - web sockets is partially working - this is very very
very exciting

But I can't get past the handshake ...

<aside>
If we can get this working we can junk ajax, comet etc and do pure
socket bi-directional
stuff as the great ones intended. Erlang will then fit *beautifully*
with the broswer
code and we can start writing some great applications
</aside>

This posting

http://blog.chromium.org/2009/12/web-sockets-now-available-in-google.html

Got me pretty excited - I happen to have the latest chrome browser as
so a little test was in order ...

The handshake is described in

http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-55#page-22

So I set up a local web server on port 2246 that serves up this page

 <body>
  <script>
    alert("hello");
    if ("WebSocket" in window) {
	var ws = new WebSocket("ws://localhost:1234");
	
	ws.onopen = function() {
	    // Web Socket is connected. You can send data by send() method.
	    ws.send("hello from the browser");
	};
	
	ws.onmessage = function (evt)
	    {
		var received_msg = evt.data; alert("yes");
	    };

	ws.onclose = function()
	    {
		alert("closed");
	    };
    } else {
	alert("sad");
    };
	
  </script>
</body>


Then I have a server on port 1234 using this code

-module(local_server).
-compile(export_all).

start() ->
    {ok, Listen} = gen_tcp:listen(1234, [{packet,0},
					 {reuseaddr,true},
					 {active, true}]),
    spawn(fun() -> par_connect(Listen) end).

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

wait(Socket) ->
    receive
	{tcp, Socket, Data} ->
	    io:format("received:~p~n",[Data]),
	    Msg = prefix() ++
		"WebSocket-Origin: http://localhost:2246\r\n" ++
		"WebSocket-Location: ws://localhost:1234\r\n\r\n",
	    gen_tcp:send(Socket, Msg),
	    loop(Socket);
	Any ->
	    io:format("Received:~p~n",[Any]),
	    wait(Socket)
    end.

prefix() ->
    "HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade:
WebSocket\r\nConnection: Upgrade\r\n".

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

It's beginning to work but now the handshake fails.

Very exciting stuff.

Be the first to get this working and tell us how

/Joe


More information about the erlang-questions mailing list