express & socket.io ta: henrique pereirahenrique.pereira/pdfs/seng513_wint… · socket.io...

Post on 22-Aug-2020

5 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

#11 – Express & Socket.IO

TA: Henrique Pereira

▪ Minimalist web framework for Node.js

▪ Routing

▪ Database integration

▪ Template Engine integration

▪ Scaffolding

▪ Real-time framework

▪ Bidirectional event-based communication

▪ Clients can send messages to the server in “real-time”

▪ Serve can communicate with the clients in “real-time”

▪ Easy to use API

▪ Integrates easily with Node.JS/Express

▪ npm init

▪ npm install express –save

▪ npm install socket.io --save

▪ Remember the Express application from last tutorial?

▪ https://jsfiddle.net/pqweuhgu/

▪ We need to make some changes.

▪ Socket.IO requires direct integration with the NodeJS HTTP Server

▪ Var server is the Node.JS HTTP Server

▪ Var io is the Socket.IO instance on top of the Node server

▪ Everything else can stay the same.

▪ https://jsfiddle.net/pqweuhgu/11/

▪ res.sendfile(file)

▪ sendfile method

▪ sendFile method

▪ Serving a static index.html?

▪ https://jsfiddle.net/pqweuhgu/12/

▪ io.on(‘connection’, f_handler(socket));▪ For every user that connects, the f_handler loop will be executed.

▪ socket is the client socket

▪ It has two useful methods

▪ .on(event, handler) – executes “handler” when clients send the “event”

▪ .emit(event, data) – sends an “event” to the client with {data}

▪ io.emit(event, data) – sends an “event” to all clients with {data}

▪ Sending a simple hello event when an user connects:

▪ https://jsfiddle.net/pqweuhgu/14/

▪ Broadcasting that an user has connected:

▪ https://jsfiddle.net/pqweuhgu/16/

▪ Load the socket.io client JS

▪ <script src="/socket.io/socket.io.js"></script>

▪ Connect to a socket.io server

▪ let socket = io.connect('http://server:port/’)

▪ Handle and emit events!

▪ socket.on(event, handler)

▪ socket.emit(event, data)

▪ https://jsfiddle.net/pqweuhgu/19/

▪ Events we want to handle:

▪ New connections

▪ The user should receive the number of times the button has been clicked

▪ Maybe we should tell other users that a new user has arriver?

▪ Button Clicks

▪ We should keep track of how many time a button has been clicked

▪ We should send the updated value to all users

▪ https://jsfiddle.net/pqweuhgu/22/

▪ Full code:

▪ https://jsfiddle.net/pqweuhgu/23/

▪ Using jQuery

▪ https://jsfiddle.net/pqweuhgu/25/

top related