Create chat.js
Browse files
chat.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const app = express();
|
| 3 |
+
const http = require('http');
|
| 4 |
+
const server = http.createServer(app);
|
| 5 |
+
const path = require('path');
|
| 6 |
+
const { Server } = require('socket.io');
|
| 7 |
+
const io = new Server(server);
|
| 8 |
+
|
| 9 |
+
app.use(express.static(path.resolve(__dirname + './public')));
|
| 10 |
+
|
| 11 |
+
app.get('/', (req, res) => {
|
| 12 |
+
res.sendFile(path.resolve(__dirname + './public/index.html'));
|
| 13 |
+
});
|
| 14 |
+
|
| 15 |
+
io.on('connection', (socket) => {
|
| 16 |
+
console.log(socket.handshake.query.name + " connected!");
|
| 17 |
+
io.emit('connection notification', socket.handshake.query.name);
|
| 18 |
+
socket.on('disconnect', () => {
|
| 19 |
+
socket.broadcast.emit('finish typing', socket.handshake.query.name);
|
| 20 |
+
console.log(socket.handshake.query.name + " disconnected!");
|
| 21 |
+
io.emit('disconnection notification', socket.handshake.query.name);
|
| 22 |
+
});
|
| 23 |
+
socket.on('chat message', (msg) => {
|
| 24 |
+
socket.broadcast.emit('chat message', msg);
|
| 25 |
+
});
|
| 26 |
+
socket.on('typing', () => {
|
| 27 |
+
socket.broadcast.emit('typing', socket.handshake.query.name);
|
| 28 |
+
});
|
| 29 |
+
socket.on('finish typing', () => {
|
| 30 |
+
socket.broadcast.emit('finish typing', socket.handshake.query.name);
|
| 31 |
+
});
|
| 32 |
+
});
|
| 33 |
+
|
| 34 |
+
server.listen(3000, () => {
|
| 35 |
+
console.log('Listening on *: 7080');
|
| 36 |
+
});
|