Skip to content

Instantly share code, notes, and snippets.

@jbanahan
Created September 25, 2020 15:59
Show Gist options
  • Save jbanahan/9491ff3f0f4b0c69bdf051d863aa54bd to your computer and use it in GitHub Desktop.
Save jbanahan/9491ff3f0f4b0c69bdf051d863aa54bd to your computer and use it in GitHub Desktop.
Example of emitters and listeners
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Listener Emitter Example</title>
</head>
<body>
<messageLocation></messageLocation>
<form id="message-form">
<input id="message">
<button>Send</button>
</form>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8006');
socket.on('yelling', function (msg) {
$('messageLocation').append($('<p>').append(msg));
});
$(function (){
$('#message-form').submit(function () {
socket.emit('yelling', $('#message').val());
})
})
</script>
</body>
</html>
var io = require('socket.io').listen(8006);
io.sockets.on('connection', function (socket) {
socket.on('yelling', function (msg){
console.log(msg);
socket.broadcast.emit('yelling', msg);
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment