Skip to content

Instantly share code, notes, and snippets.

@nicokaiser
Created June 25, 2013 15:52
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nicokaiser/5859603 to your computer and use it in GitHub Desktop.
WAMP.IO example
<!DOCTYPE html>
<html>
<head>
<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js">
</script>
<script>
// WAMP session object
var sess;
var wsuri = "ws://localhost:9000";
window.onload = function() {
// connect to WAMP server
ab.connect(wsuri,
// WAMP session was established
function (session) {
sess = session;
console.log("Connected to " + wsuri);
// subscribe to topic, providing an event handler
sess.subscribe("http://example.com/simple", onEvent);
},
// WAMP session is gone
function (code, reason) {
sess = null;
console.log("Connection lost (" + reason + ")");
}
);
};
function onEvent(topic, event) {
console.log(topic);
console.log(event);
}
function publishEvent()
{
sess.publish("http://example.com/simple", {a: "foo", b: "bar", c: 23});
}
function callProcedure() {
// issue an RPC, returns promise object
sess.call("http://example.com/simple/calc#add", 23, 7).then(
// RPC success callback
function (res) {
console.log("got result: " + res);
},
// RPC error callback
function (error, desc) {
console.log("error: " + desc);
}
);
}
</script>
</head>
<body>
<h1>AutobahnJS WAMP Client</h1>
<button onclick="publishEvent();">Publish Event</button>
<button onclick="callProcedure();">Call Procedure</button>
</body>
</html>
/**
* Module dependencies.
*/
var http = require('http')
, qs = require('querystring')
, WebSocketServer = require('ws').Server
, wamp = require('wamp.io');
/**
* WebSocket server
*/
var wss = new WebSocketServer({ port: 9000 });
var app = wamp.attach(wss);
/**
* REST API
*/
var api = http.createServer(function(req, res) {
if (req.url !== '/hub') {
res.writeHead(404);
res.end('Not Found');
return;
}
if (req.method !== 'POST') {
res.writeHead(405);
res.end('Method Not Allowed');
return;
}
var buffer = '';
req.on('data', function(data) {
buffer += data;
});
req.on('end', function() {
var topicUri, event;
try {
var parsed = qs.parse(buffer);
topicUri = parsed.topicuri;
event = JSON.parse(parsed.body);
} catch (e) {
res.writeHead(400);
res.end('invalid JSON in request body');
return;
}
app.publish(topicUri, event);
res.writeHead(202);
res.end();
});
req.on('close', function() {
buffer = '';
});
});
api.listen(9090);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment