-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
70 lines (57 loc) · 1.96 KB
/
app.js
File metadata and controls
70 lines (57 loc) · 1.96 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
// --- 1. IMPORTS & SETUP ---
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const http = require("http");
const path = require("path"); // Penting untuk kirim file HTML
const { Server } = require("socket.io");
// Inisialisasi App
const app = express();
const PORT = process.env.PORT || 3000;
// Bungkus Express dengan HTTP Server (Wajib untuk Socket.io)
const server = http.createServer(app);
// Setup Socket.io
const io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
// --- 2. MIDDLEWARE ---
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
// [PENTING] Jadikan folder ini PUBLIC agar client.js dan style.css bisa dibaca browser
app.use(express.static(__dirname));
// --- 3. ROUTES ---
// Route Utama: Saat buka localhost:3000, kirim index.html
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
});
// --- 4. LOGIKA SOCKET (Jantung Aplikasi Chat) ---
io.on("connection", (socket) => {
console.log(`⚡ User Connected: ${socket.id}`);
// Event: User join ke room
socket.on("join_room", (room) => {
socket.join(room);
console.log(`User ${socket.id} joined room: ${room}`);
});
// Event: User kirim pesan
socket.on("send_message", (data) => {
console.log(`Message from ${data.username}: ${data.message}`);
// Broadcast pesan ke orang lain di room yang sama
socket.to(data.room).emit("receive_message", data);
});
// Event: User keluar
socket.on("disconnect", () => {
console.log("User Disconnected", socket.id);
});
});
// --- 5. START SERVER ---
// Gunakan 'server.listen' (bukan app.listen)
server.listen(PORT, () => {
console.log(`\n🚀 ASync Realtime Server berjalan di port: ${PORT}`);
console.log(`🔗 Buka di browser: http://localhost:${PORT}`);
});