There's more...

So far, we have seen that we can share the same underlying HTTP server between ExpressJS and Socket.IO. However, that is not all.

The reason why we define a Socket.IO path is actually useful when working with ExpressJS. Take the following example:

const express = require('express') 
const io = require('socket.io')() 
const app = express() 
io.path('/socket.io')
app.get('/socket.io', (req, res) => { res.status(200).send('Hey there!') }) io.of('/').on('connection', socket => { socket.emit('someEvent', 'Data from Server!') }) io.attach(app.listen(1337))

As you can see, we are using the same URL path for Socket.IO and ExpressJS. We accept new connections to the Socket.IO server on the /socket.io path, but we also send content for /socket.io using the GET route method.

Even though this preceding example won't actually break your application, make sure to never use the same URL path to serve content from ExpressJS and accept new connections for Socket.IO at the same time. For instance, changing the previous code to this:

io.path('/socket.io')
app.get('/socket.io/:msg', (req, res) => { res.status(200).send(req.params.msg) })

While you may expect your browser, when visiting http://localhost:1337/socket.io/message, to display message, that won't be the case and you will see the following instead:

{"code":0,"message":"Transport unknown"} 

That is because Socket.IO will interpret the incoming data first and it won't understand the data you just sent. In addition, your route handler will never be executed.

Besides that, the Socket.IO server also serves, by default, its own Socket.IO Client under the defined URL path. For example, try visiting http://localhost:1337/socket.io/socket.io.js and you will be able to see the minimized JavaScript code of the Socket.IO client.

If you wish to server your own version of Socket.IO client or if it is included in the bundle of your application, you can disable the default behavior in your Socket.IO server application with the serveClient method:

io.serveClient(false) 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.107.94