Create a Socket.IO client application that will connect to the Socket.IO server, that you will build next, and display a welcome message sent by the server.
- Create a new file named io-express-view.html
- Add the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Socket.IO Client</title> <script src="http://localhost:1337/socket.io/socket.io.js">
</script> <script
src="https://unpkg.com/@babel/standalone/babel.min.js">
</script> </head> <body> <h1 id="welcome"></h1> <script type="text/babel"> const welcome = document.getElementById('welcome') const manager = new io.Manager( 'http://localhost:1337', { path: '/socket.io' }, ) const root = manager.socket('/') root.on('welcome', (msg) => { welcome.textContent = msg }) </script> </body> </html>
- Save the file
Next, build an ExpressJS application and a Socket.IO server. The ExpressJS application will serve the previously created HTML file on the root path "/":
- Create a new file named io-express-server.js
- Initialize a new Socket.IO server application and an ExpressJS application:
const path = require('path') const express = require('express') const io = require('socket.io')() const app = express()
- Define the URL path where new connections will be made to the Socket.IO server:
io.path('/socket.io')
- Define a route method to serve our HTML file containing our Socket.IO client application:
app.get('/', (req, res) => { res.sendFile(path.resolve( __dirname, 'io-express-view.html', )) })
- Define a namespace "/" and emit a welcome event with welcome message:
io.of('/').on('connection', (socket) => { socket.emit('welcome', 'Hello from Server!') })
- Attach the Socket.IO to ExpressJS Server:
io.attach(app.listen(1337, () => { console.log( 'HTTP Server and Socket.IO running on port 1337' ) }))
- Save the file
- Open the Terminal and run:
node io-express-server.js
- In your browser, visit:
http://localhost:1337/