Testing web sockets
by zerrax
HTML
<p>Open the console. Messages are logged in the console log.</p>
<button id="send-message">Send Message</button>
JavaScript
var connection = new WebSocket('ws://localhost:1337');
// When the connection is open, send some data to the server
connection.onopen = function () {
console.log('Client: Hello! Connection is open at ', new Date());
connection.send('Hello! Connection is open'); // Send the message 'Ping' to the server
};
// Log errors
connection.onerror = function (error) {
console.log('WebSocket Error ', error);
};
// Log messages from the server
connection.onmessage = function (e) {
console.log('Server: ', e.data, ' at ', new Date());
};
var $sendMessageBtn = document.getElementById('send-message');
$sendMessageBtn.addEventListener('click', sendMessage);
function sendMessage(){
console.log('Client: Sending message!!!! at ', new Date());
connection.send('Sending message!!!!');
}