-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (56 loc) · 1.65 KB
/
server.js
File metadata and controls
66 lines (56 loc) · 1.65 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
const express = require("express");
const http = require("http");
const path = require("path");
const socketIo = require("socket.io");
// Create Express app
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, "public")));
// Socket.IO connection handling
io.on("connection", (socket) => {
console.log("A user connected:", socket.id);
// Welcome message to the connected user
socket.emit("message", {
user: "System",
text: "Welcome to the chat!",
time: new Date().toLocaleTimeString(),
});
// Broadcast to all other users that someone joined
socket.broadcast.emit("message", {
user: "System",
text: "A new user has joined the chat",
time: new Date().toLocaleTimeString(),
});
// Handle chat messages
socket.on("chatMessage", (msg) => {
io.emit("message", {
user: msg.user,
text: msg.text,
time: new Date().toLocaleTimeString(),
});
});
// Handle typing events
socket.on("typing", (username) => {
socket.broadcast.emit("typing", username);
});
// Handle when user stops typing
socket.on("stopTyping", () => {
socket.broadcast.emit("stopTyping");
});
// Handle disconnection
socket.on("disconnect", () => {
console.log("User disconnected:", socket.id);
io.emit("message", {
user: "System",
text: "A user has left the chat",
time: new Date().toLocaleTimeString(),
});
});
});
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});