-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
66 lines (52 loc) · 1.49 KB
/
app.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/** app for groupchat */
const express = require('express');
const app = express();
// serve stuff in static/ folder
app.use(express.static('static/'));
/** Handle websocket chat */
// allow for app.ws routes for websocket routes
const wsExpress = require('express-ws')(app);
const ChatUser = require('./ChatUser');
/** Handle a persistent connection to /chat/[roomName]
*
* Note that this is only called *once* per client --- not every time
* a particular websocket chat is sent.
*
* `ws` becomes the socket for the client; it is specific to that visitor.
* The `ws.send` method is how we'll send messages back to that socket.
*/
app.ws('/chat/:roomName', function(ws, req, next) {
try {
const user = new ChatUser(
ws.send.bind(ws), // fn to call to message this user
req.params.roomName // name of room for user
);
// register handlers for message-received, connection-closed
ws.on('message', function(data) {
try {
user.handleMessage(data);
} catch (err) {
console.error(err);
}
});
ws.on('close', function() {
try {
user.handleClose();
} catch (err) {
console.error(err);
}
});
} catch (err) {
console.error(err);
}
});
/** serve homepage --- just static HTML
*
* Allow any roomName to come after homepage --- client JS will find the
* roomname in the URL.
*
* */
app.get('/:roomName', function(req, res, next) {
res.sendFile(`${__dirname}/chat.html`);
});
module.exports = app;