A Socket.IO server will be built to respond to a single event named time. When the event is fired, it will get the server's current time and emit another event named "got time?" providing two arguments, the current time and a counter that specifies how many times a request was made.
- Create a new file named simple-io-server.js
- Include the Socket.IO module and initialize a new server:
const io = require('socket.io')()
- Define the URL path where connections will be made:
io.path('/socket.io')
- Use the root or "/" namespace:
const root = io.of('/')
- When a new connection is made, initialize a counter variable to 0. Then, add a new listener to the time event that will increase the counter by one, every time there is a new request, and emit the "got time?" event that will be later defined on the client side:
root.on('connection', socket => { let counter = 0 socket.on('time', () => { const currentTime = new Date().toTimeString() counter += 1 socket.emit('got time?', currentTime, counter) }) })
- Listen on port 1337 for new connections:
io.listen(1337)
- Save the file
Next, build a Socket.IO client that will connect to our server:
- Create a new file named simple-io-client.js
- Include the Socket.IO client module:
const io = require('socket.io-client')
- Initialize a new Socket.IO client providing the server URL and an options object where we will define the path used in the URL where the connections will be made:
const clientSocket = io('http://localhost:1337', { path: '/socket.io', })
- Add an event listener to the connect event. Then, when a connection is made, using a for loop, emit the time event 5 times:
clientSocket.on('connect', () => { for (let i = 1; i <= 5; i++) { clientSocket.emit('time') } })
- Add an event listener to the "got time?" event that will expect to receive two arguments the time and a counter that specifies how many requests were made to the server, then print on the console:
clientSocket.on('got time?', (time, counter) => { console.log(counter, time) })
- Save the file
- Open a Terminal and run first the Socket.IO server:
node simple-io-server.js
- Open another terminal and run the Socket.IO client:
node simple-io-client.js