-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
52 lines (33 loc) · 1.17 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const http = require("http");
const express = require("express");
const cors = require("cors");
const socketIO = require("socket.io");
const app = express();
const port = 4000 || process.env.PORT;
app.use(cors());
app.get("/", (req, res) => {
res.send("WORKING");
})
const server = http.createServer(app);
const io = socketIO(server);
app.get("/", (req, res) => {
res.send("WORKING");
});
const users = [{}];
io.on("connection", (socket) => {
console.log("New Connection");
socket.on('joined', ({ user }) => {
users[socket.id] = user;
socket.emit('welcome', { user: "Admin", message: `Welcome to the chat ${users[socket.id]} ` });
socket.broadcast.emit('userJoined', { user: "Admin", message: ` ${users[socket.id]} has joined`, id: socket.id });
})
socket.on('disconnect', () => {
socket.broadcast.emit('leave', { user: "Admin", message: `${users[socket.id]} has left`, id: socket.id });
})
socket.on('message', ({ message, id }) => {
io.emit('sendMessage', { user: users[id], message, id });
})
});
server.listen(port, () => {
console.log(`server is working on http://localhost:${port}`);
});