Last active
November 4, 2019 12:51
-
-
Save SuperOleg39/27bdcacdf3eed03c09e29bcd9179a1d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const WebSocket = require('ws'); | |
| const fs = require('fs'); | |
| const path = require('path'); | |
| const http = require('http'); | |
| const redis = require('redis'); | |
| const redisList = redis.createClient(); | |
| const redisSub = redis.createClient(); | |
| const redisPub = redis.createClient(); | |
| // раздача статики, код можно игнорировать | |
| const server = http.createServer(function (req, res) { | |
| const url = req.url === '/' ? | |
| path.join(__dirname, 'www', 'index.html') : | |
| path.join(__dirname, 'www', req.url); | |
| fs.readFile(url, (err, data) => { | |
| if (err) { | |
| res.writeHead(404); | |
| res.end(JSON.stringify(err)); | |
| return; | |
| } | |
| res.writeHead(200); | |
| res.end(data); | |
| }); | |
| }).listen(process.argv[2] || 4444); | |
| const wss = new WebSocket.Server({server}); | |
| wss.on('connection', (ws) => { | |
| console.log('Client connected'); | |
| // при первом соединении отдаем клиенту сообщения из истории | |
| redisList.lrange('messages-archive', 0, -1, (error, messages) => { | |
| ws.send(JSON.stringify({ | |
| type: 'chat-history', | |
| payload: messages | |
| })); | |
| }); | |
| redisList.llen('messages-archive', console.log) | |
| ws.on('message', (message) => { | |
| console.log(`Message: ${message}`); | |
| // записываем сообщение в историю | |
| redisList.rpush('messages-archive', message); | |
| // отправляем сообщение в брокер | |
| redisPub.publish('chat-messages', message); | |
| }); | |
| }); | |
| redisSub.subscribe('chat-messages'); | |
| // отправляем сообщение из брокера всем клиентам | |
| redisSub.on('message', (channel, message) => { | |
| wss.clients.forEach((client) => { | |
| client.send(JSON.stringify({ | |
| type: 'new-message', | |
| payload: message | |
| })); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment