You are on page 1of 10

Node.

js -
Websockets
Emerging Web Technologies
Mohawk College
Imagine making something like Slack with PHP (i.e. LAMP stack)

… how would you do it?


Real-time web applications
• Real-time web applications allow clients to receive
information exactly when it is published, rather
than periodically check the server for updates

• Updates are pushed to clients from the server,


rather than having the client pull information from
the server
Real-time web applications
• Real-time web applications are more than chat…

• A dashboard responding to…


• Changes in Internet of Things sensor values
• Changes in stock market values

• Give teachers real-time feedback and interaction


with students accessing a service from their devices
WebSockets
• Previously discussed WebStockets as full-duplex
protocol that allows streams of messages back and
forth between server and client

• We can use Websockets to interface with real-time


applications, and to create them ourselves…

• Socket.io is the library that implements Websockets


for NodeJS and front-end:
• http://socket.io/
Socket.io back-end
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){


res.sendFile(__dirname + '/index.html');});

io.on('connection', function(socket) {
socket.on('chat message', function(msg){
io.emit('chat message', msg); });});

http.listen(3000, function(){ console.log('listening on *:3000');});


Socket.io front-end
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io();
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg) {
$('#messages').append($('<li>').text(msg));
});
</script>
Socket.io
• Notice that both the server and client can both emit messages and
respond to messages (with on)
• That is the core idea when using websockets...  listening for messages and
sending messages

• Client involves including a JavaScript library

• WebSockets chat example:


• http://socket.io/get-started/chat/

• Socket.io package: 
• https://www.npmjs.com/package/socket.io
• Start with npm install socket.io
Let's go over some examples!
• See WebsocketExamples.zip on MyCanvas

• Chat example

• Teacher and student quiz example


• Should be helpful for Assignment #3

• Notice in particular the different ways we can emit messages


across these above examples

• Settimeout() example may also be helpful!


Resources
• Websockets:
• http://socket.io/
• http://socket.io/get-started/chat/

You might also like