Skip to content

Instantly share code, notes, and snippets.

@markomitranic
Created July 16, 2018 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markomitranic/c6a1d9e0617562eeecaff23a85518899 to your computer and use it in GitHub Desktop.
Save markomitranic/c6a1d9e0617562eeecaff23a85518899 to your computer and use it in GitHub Desktop.
Basic WebSocket Ping-Pong Implementation
var socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('error', function(message) {
console.log('Wow guy, there was an eror.');
console.log('Heres the message:', message);
});
socket.addEventListener('open', function(message) {
console.log('Open now!!');
console.log('Heres the message:', message);
setTimeout(function() {
sendMessage();
}, 3000);
});
socket.addEventListener('close', function(message) {
console.log('Socket is closed now.');
console.log('Heres the message:', message);
});
socket.addEventListener('message', function(message) {
console.log('A NEW MESSAGE!!');
console.log('Heres the message:', message);
});
function sendMessage() {
console.log('SENDING MESSAGE...');
socket.send("Hello earthlings!");
}
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', function(client) {
console.log('a new client is here!');
client.on('close', function(ws) {
console.log('User has left. :(');
});
client.on('message', function(message) {
console.log('heres a message from client:', message);
client.send(message);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment