问题
I have the following lines of code in my index.js file:
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io').listen(server);
When I start my server with: node --inspect server/index.js
I get: TypeError: require(...).listen is not a function.
Any and all help appreciated!
回答1:
You need http server. The correct way to start a socket server is,
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app)
const socketio = require('socket.io')
const io = socketio(server);
io.on("connection", socket => {
console.log("connected");
socket.on("welcome", (data) => {
console.log("welcome message", data);
})
});
server.listen(3000, () => console.log(`listen on port ${port}`))
The client,
const io = require("socket.io-client");
let socket = io.connect("http://localhost:3000");
socket.emit("welcome", "Hi");
来源:https://stackoverflow.com/questions/65265662/how-do-i-fix-a-server-side-socket-io-error