Express & Socket.IO TA: Henrique Pereirahenrique.pereira/pdfs/seng513_wint… · Socket.IO requires...
Transcript of Express & Socket.IO TA: Henrique Pereirahenrique.pereira/pdfs/seng513_wint… · Socket.IO requires...
#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/