Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Created August 21, 2010 03:37
Show Gist options
  • Select an option

  • Save leandrosilva/541724 to your computer and use it in GitHub Desktop.

Select an option

Save leandrosilva/541724 to your computer and use it in GitHub Desktop.
Misultin: erlang and websockets
Source code copied-pasted from blog post titled "Misultin: erlang and websockets".
http://www.ostinelli.net/misultin-erlang-and-websockets/
This is based on misultin, an Erlang library for building fast lightweight HTTP(S) servers.
http://code.google.com/p/misultin/
-module(misultin_websocket_example).
-export([start/1, stop/0]).
% start misultin http server
start(Port) ->
misultin:start_link([{port, Port}, {loop, fun(Req) -> handle_http(Req, Port) end}, {ws_loop, fun(Ws) -> handle_websocket(Ws) end}]).
% stop misultin
stop() ->
misultin:stop().
% callback on request received
handle_http(Req, Port) ->
% output
Req:ok([{"Content-Type", "text/html"}],
["
<html>
<head>
<script type=\"text/javascript\">
function addStatus(text){
var date = new Date();
document.getElementById('status').innerHTML = document.getElementById('status').innerHTML
+ date + \": \" + text + \"<br>\";
}
function ready(){
if (\"WebSocket\" in window) {
// browser supports websockets
var ws = new WebSocket(\"ws://localhost:", integer_to_list(Port) ,"/service\");
ws.onopen = function() {
// websocket is connected
addStatus(\"websocket connected!\");
// send hello data to server.
ws.send(\"hello server!\");
addStatus(\"sent message to server: 'hello server'!\");
};
ws.onmessage = function (evt) {
var receivedMsg = evt.data;
addStatus(\"server sent the following: '\" + receivedMsg + \"'\");
};
ws.onclose = function() {
// websocket was closed
addStatus(\"websocket was closed\");
};
} else {
// browser does not support websockets
addStatus(\"sorry, your browser does not support websockets.\");
}
}
</script>
</head>
<body onload=\"ready();\">
<div id=\"status\"></div>
</body>
</html>"]).
% callback on received websockets data
handle_websocket(Ws) ->
receive
{browser, Data} ->
Ws:send(["received '", Data, "'"]),
handle_websocket(Ws);
_Ignore ->
handle_websocket(Ws)
after 5000 ->
Ws:send("pushing!"),
handle_websocket(Ws)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment