-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.js
45 lines (31 loc) · 1.04 KB
/
socket.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
// server.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server,{
cors: {origin:"*"}
});
const connectedUsers = new Set();
io.on('connection', (socket) => {
console.log(`A user connected: ${socket.id}`);
socket.on('joinChat', (username) => {
socket.join('chatroom');
connectedUsers.add(socket.id);
const userDisplayName = username || 'Anonymous';
io.to('chatroom').emit('userJoined', userDisplayName);
socket.on('sendMessage', (message) => {
io.to('chatroom').emit('messageReceived', { user: userDisplayName, message });
});
socket.on('disconnect', () => {
console.log(`A user disconnected: ${socket.id}`);
connectedUsers.delete(socket.id);
io.to('chatroom').emit('userLeft', userDisplayName);
});
});
});
const PORT = process.env.PORT || 4001;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});