jipp
January 12, 2023, 5:01pm
1
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")
})
Were you able to figure it out?
jipp
January 12, 2023, 6:38pm
6
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")
})
})
jipp
January 13, 2023, 12:40am
9
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