-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
43 lines (36 loc) · 1.33 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
// Required modules
const express = require('express')
// Create an express app
const app = express()
// Create an HTTP server based on the express app
const http = require('http').Server(app)
// Attach Socket.io to the HTTP server
const io = require('socket.io')(http)
const path = require('path')
// Define a default port or fetch from environment variables
const port = process.env.PORT || 8080
// Define the default route for the application. Send the HTML file when accessed.
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'src/index.html'))
})
// Event listener for a new Socket.io connection
io.on('connection', (socket) => {
console.log(`User ${socket.id} connected`) // Log when a user connects
// Event listener for user disconnect
socket.on('disconnect', () => console.log(`User ${socket.id} disconnected`))
// Event listener for messages from the client
socket.on('clientMessage', (message) => {
//console.log(`Client message "${message}"`)
console.log(message)
io.emit(
'client has written',
`Received message from ${message.clientId}: ${message.message}`
)
})
// Send a message to the connected client
socket.emit('serverMessage', 'Hello from server')
})
// Start the HTTP server on the defined port
http.listen(port, () => {
console.log(`App listening on port ${port}`)
})