Complete the code to create a basic Express server that listens on port 3000.
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen([1], () => { console.log('Server running'); });
The standard port for local Express servers is often 3000. This code starts the server on port 3000.
Complete the code to import and use the Socket.IO library for real-time communication.
const http = require('http'); const express = require('express'); const app = express(); const server = http.createServer(app); const io = require('[1]')(server); io.on('connection', (socket) => { console.log('A user connected'); });
Socket.IO is the library used to enable real-time, bidirectional communication between web clients and servers.
Fix the error in the code to emit a message to the connected client.
io.on('connection', (socket) => { socket.[1]('message', 'Hello everyone!'); });
The emit method sends an event with data to the client. Here, it sends a 'message' event.
Fill both blanks to broadcast a message to all clients except the sender.
io.on('connection', (socket) => { socket.[1].[2]('message', 'Hello others!'); });
Using socket.broadcast.emit sends a message to all clients except the one that sent it.
Fill all three blanks to set up a server that listens on port 4000 and sends a welcome message on connection.
const express = require('express'); const http = require('http'); const app = express(); const server = http.createServer(app); const io = require('[1]')(server); io.on('connection', ([2]) => { [2].emit('welcome', 'Welcome to the real-time server!'); }); server.listen([3], () => { console.log('Server listening on port 4000'); });
This code imports Socket.IO, names the connection parameter 'socket', and listens on port 4000.