Skip to content

Instantly share code, notes, and snippets.

@narate
Created August 7, 2014 07:57
Show Gist options
  • Save narate/68cb4c38e1234235bec7 to your computer and use it in GitHub Desktop.
Save narate/68cb4c38e1234235bec7 to your computer and use it in GitHub Desktop.
Simple WebSocker listener
<!DOCTYPE html>
<html>
<head>
<style>
#logs_content {
border: 1px solid red;
width:98%;
height: 480px;
position:relative;
bottom:0px;
top:0px;
overflow:auto;
padding: 10px;
}
</style>
<script>
var connection = null;
var url = "ws://websocket-url/";
var ch = "hello";
function send(){
var json = {};
json.message = {}
json.message.date = new Date();
connection.send(JSON.stringify(json));
console.log("Send: " + JSON.stringify(json));
}
function setChannel(){
connection = null;
ch = document.getElementById('ch').value;
uri = url + ch
document.getElementById('uri').innerHTML = uri;
connection = new WebSocket(uri);
// When the connection is open, send some data to the server
connection.onopen = function() {
// connection.send('{"message":{"msg":"Ping"}}'); // Send the message 'Ping' to the server
console.log('Connected');
};
// Log errors
connection.onerror = function(error) {
console.log('WebSocket Error ' + JSON.stringify(error));
};
// Log messages from the server
connection.onmessage = function(e) {
console.log("Received : " + e.data);
var json = JSON.parse(e.data);
var ol = document.getElementById('logs');
var li = document.createElement('li');
li.appendChild(document.createTextNode(e.data));
ol.appendChild(li);
var logs_content = document.getElementById('logs_content');
logs_content.scrollTop = logs_content.scrollHeight;
}
}
</script>
<style>
body {
font-family: "Monaco", monospace;
}
</style>
</head>
<body>
<label for="ch">Channel</label>
<input type="text" id="ch" name='ch' placeholder="channel"/>
<button onclick="setChannel()">Set channel</button>
<button onClick="send()">Send</button>
<p id="uri">uri : ...</p>
<code>
<label for="logs_content">Output</label>
<div id='logs_content' name='logs_content'>
<ol id='logs'></ol>
</div>
</code>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment