-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
82 lines (73 loc) · 2.3 KB
/
Copy pathserver.js
File metadata and controls
82 lines (73 loc) · 2.3 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { Server } from "socket.io";
import { createServer } from "http";
import "dotenv/config";
import express from "express";
import process from 'process';
import bodyParser from 'body-parser';
import {v4} from 'uuid'
import session from 'express-session'
import router from './routes/index.js'
import roomManage from "./utils/room.js";
const port = process.env.SOCKETPORT || 5001;
const host = process.env.SOCKETHOST || '0.0.0.0';
const app = express()
const httpServer = createServer(app);
if (!process.env.SECRETKEY) {
process.env.SECRETKEY = v4();
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
secret: process.env.SECRETKEY,
resave: false,
saveUninitialized: true,
cookie: {
secure: false,
httpOnly: false,
maxAge: 1000 * 60 * 60 * 24
},
}));
app.use(router);
app.use(express.static('./frontend'))
roomManage.createRoom("general", undefined,"general topic all starts with it")
.catch(err => {
console.log(err)
})
const io = new Server(httpServer, { cors: { origin: "*" } })
io.on('connection', soc => {
soc.on('username', (name) => {
soc.username = name;
})
console.log('user:', soc.id, 'connected')
soc.on('joinRoom', roomName => {
if (!soc.username) {
console.log('username not recieved yet, trying to reconnect....')
soc.emit("rejoin", {status: "failed to join room"})
return;
}
if(soc.currentRoom) {
soc.leave(soc.currentRoom);
io.to(soc.currentRoom).emit('announcement', soc.username + ' has left the room');
}
soc.currentRoom = roomName;
soc.join(soc.currentRoom);
console.log(soc.username, "has joined", soc.currentRoom)
io.to(soc.currentRoom).emit('joined', soc.currentRoom)
io.to(soc.currentRoom).emit('announcement', `user ${soc.username} has joined the room`)
soc.on('message', (message) => {
console.log('message sent to', soc.currentRoom);
soc.broadcast.to(soc.currentRoom).emit('message', JSON.stringify({message, username: soc.username}))
})
})
soc.on('disconnect', () => {
console.log(soc.username, "left", soc.currentRoom)
if(soc.currentRoom) {
soc.leave(soc.currentRoom);
io.to(soc.currentRoom).emit('announcement', soc.username + ' has left the room');
soc.currentRoom = null;
}
})
})
httpServer.listen(port, host, () => {
console.log('socket connection started on',host, port);
})