简体   繁体   中英

Socket.io is not found in the client-side

This is my Server Side:

const path = require('path');
const http = require('http');
const express = require('express');

const socketio = require('socket.io');

const app = express();
 
const server = http.createServer(app);
const io = socketio(server);
const port = 3000 || process.env.PORT;

app.listen(port, () => {
console.log(`server running on port ${port}`);
});

io.on('connection', socket => {
console.log(socket);
});

This is my Client Side:

   <script src="/socket.io/socket.io.js"></script>
   <script>
   const socket = io();
   </script>
   </body>

   </html>

I re-installed all the modules correctly, but it did not help.

The problem is that you're creating two web servers, attaching socket.io to one of them, but only starting the other one.

Both of these lines of code create a new web server:

const server = http.createServer(app);
app.listen(port, ...);

But, only the second one actually gets started and that's NOT the one you bound socket.io to. So, the server you bound socket.io to is never started, therefore none of the client-side stuff that is supposed to talk to your socket.io server will work properlly.


To fix it, change your server code to this:

const path = require('path');
const express = require('express');
const socketio = require('socket.io');

const app = express();
const port = 3000 || process.env.PORT;
const server = app.listen(port, () => {
    console.log(`server running on port ${port}`);
});

const io = socketio(server);

io.on('connection', socket => {
    console.log(socket);
});

Now, you will only be creating one web server, starting that server and binding socket.io to that one server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM