Need help with NodeJS socket.io code

Hello

I was working on this socket.io chat app and I was wondering how I would make a user left the chat function for this code similiar to the join function

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

const app = express();
const httpserver = http.Server(app);
const io = socketio(httpserver);

const gamedirectory = path.join(__dirname, "html");

app.use(express.static(gamedirectory));

httpserver.listen(3000);

var rooms = [];
var usernames = [];

io.on('connection', function(socket){

  socket.on("join", function(room, username){
    if (username != ""){
      rooms[socket.id] = room;
      usernames[socket.id] = username;
      socket.leaveAll();
      socket.join(room);
      io.in(room).emit("recieve", "Console : " + username + " has entered the chat.");
      socket.emit("join", room);
    }
  })
  
  socket.on("send", function(message){
    io.in(rooms[socket.id]).emit("recieve", usernames[socket.id] +" : " + message);
  })

  socket.on("recieve", function(message){
    socket.emit("recieve", message);
  })
})

If anyone could help that will be appreciated and I will credit you in my repl

Use

socket.on("disconnect", () => {
console.log("user left")
})

(post deleted by author)

Were you able to figure it out?

No, I do not where to implement it and make a command similiar to the join one. Is there a tutorial I could use that you know of?

There are some helpful resources in the socket.io website docs.

You would need to do smth like this (full code):

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

const app = express();
const httpserver = http.Server(app);
const io = socketio(httpserver);

const gamedirectory = path.join(__dirname, "html");

app.use(express.static(gamedirectory));

httpserver.listen(3000);

var rooms = [];
var usernames = [];

io.on('connection', function(socket){

  socket.on("join", function(room, username){
    if (username != ""){
      rooms[socket.id] = room;
      usernames[socket.id] = username;
      socket.leaveAll();
      socket.join(room);
      io.in(room).emit("recieve", "Console : " + username + " has entered the chat.");
      socket.emit("join", room);
    }
  })
  
  socket.on("send", function(message){
    io.in(rooms[socket.id]).emit("recieve", usernames[socket.id] +" : " + message);
  })

  socket.on("recieve", function(message){
    socket.emit("recieve", message);
  })

  socket.on("disconnect", function(message){
    // here you would so a socket.emit to tell people that this person disconnected
    console.log(username[socket.id] +" disconnected")
  })
})

Thanks you so much this helps alot. Im really new to NodeJS and the code was from the socket docs so I need help on how to do a socket emit. Where could I find it on the docs

1 Like

Here’s the emit cheatsheet for v4.x.