Skip to content

Instantly share code, notes, and snippets.

@smulube
Created May 17, 2012 12:06
Show Gist options
  • Save smulube/2718463 to your computer and use it in GitHub Desktop.
Save smulube/2718463 to your computer and use it in GitHub Desktop.
Basic Cosm WebSocket example
<html>
<head>
<title>Socket Test</title>
</head>
<body>
<h1>Cosm Websocket Test</h1>
<p>Status: <span id="status"></span></p>
<p>Current value: <span id="current_value"></span></p>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var api_key = 'YOUR_API_KEY';
var resource = '/feeds/YOUR_FEED_ID';
// Use the Pachube beta websocket server
ws = new WebSocket("ws://beta.pachube.com:8080/");
ws.onerror = function(evt) {
$('#status').html("Error: could not open WebSocket connection");
}
ws.onclose = function(evt) {
$('#status').html("Closed: WebSocket connection closed, try refreshing your browser");
}
ws.onopen = function(evt) {
$('#status').html("Connected");
ws.send('{"headers":{"X-ApiKey":"' + api_key + '"}, "method":"subscribe", "resource":"' + resource + '"}');
}
ws.onmessage = function(evt) {
data = evt.data;
response = JSON.parse(data);
if (response.body) {
$('#current_value').html(response.body.datastreams[0].current_value);
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment