Skip to content Skip to sidebar Skip to footer

How Do I Fix A Server Side Socket.io Error?

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

Solution 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");

Post a Comment for "How Do I Fix A Server Side Socket.io Error?"