Home > Back-end >  socket.io 'on' doesn't get fired with Nodejs server
socket.io 'on' doesn't get fired with Nodejs server

Time:06-14

server.js

const express_l = require('express');
const path_l    = require('path');
const app_l     = express_l();
const http_l    = require('http');

const server_l   = http_l.createServer( app_l);

const socketio_l = require('socket.io');
const io_l = socketio_l( server_l);

app_l.use( express_l.static( path_l.join( __dirname, 'public')) );

io_l.on( "connection", argSocket => { console.log('New websocket connection!'); });

var PORT = 3000 || process.env.PORT;

server_l.listen( PORT, ()=>{ console.log(`from express server on port ${PORT}!`) });

main.js

const socket = io_l();

chat.html

...
...
  <script src = "/socket.io/socket.io.js"> </script>
  <script src = "js/main.js"> </script>
</body>
</html>

package.json

{
  "name": "chatcord",
  "version": "1.0.0",
  "description": "Realtime chat application built with Nodejs",
  "main": "server.js",
  "scripts": {
    "start": "node server",
    "dev": "nodemon server"  
  },
  "author": "xyz",
  "license": "MIT",
  "dependencies": {
    "express": "^4.18.1",
    "moment": "^2.29.3",
    "socket.io": "^4.5.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.16"
  }
}

Now, when I refresh http://localhost:3000/ in browser, I don't see the console.log statement from the on function of socket.io.

Where am I going wrong? Please point out.

CodePudding user response:

Your initialization is wrong. You have create an new instance of the socket io server and then call it. Check the documentation for more. https://socket.io/get-started/chat#integrating-socketio

const { Server } = require("socket.io");
const io = new Server(server);

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

Hopefully this helps.

CodePudding user response:

this is from socket io documentation https://socket.io/get-started/chat

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

io.on("connection", async (socket) => {
  console.log("someone connected to socket")
  //add listener here
  socket.on("chat",(data)=> {
    console.log(data)
  })
});

httpServer.listen(port, host, () => {
 console.log(`Server running on http://${host}:${port}`);
});


also this is the emit cheatsheet maybe useful for you https://socket.io/docs/v3/emit-cheatsheet/

CodePudding user response:

You're consoling on nodejs server so check your terminal for the output of the console. You need to research how emitting events works in socket (helping material)

  • Related