Created
July 16, 2018 16:08
-
-
Save markomitranic/c6a1d9e0617562eeecaff23a85518899 to your computer and use it in GitHub Desktop.
Basic WebSocket Ping-Pong Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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