You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.4 KiB

3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
  1. const express = require("express");
  2. const app = express();
  3. const server = require('http').createServer(app);
  4. const io = require('socket.io')(server, {
  5. cors: {
  6. origin: "http://127.0.0.1:8000",
  7. methods: ["GET", "POST"],
  8. }
  9. });
  10. const redisAdapter = require('socket.io-redis');
  11. const redis = require("redis");
  12. const subscriber = redis.createClient({host: '127.0.0.1', port: 6379, password: 'root'});
  13. //setup redis
  14. io.adapter(redisAdapter({host: '127.0.0.1', port: 6379, password: 'root'}));
  15. // parse application/x-www-form-urlencoded
  16. app.use(express.urlencoded({ extended: false }));
  17. // parse application/json
  18. app.use(express.json());
  19. // server main route
  20. app.get('/', (req, res) => {
  21. res.sendFile(__dirname + '/static/index.html');
  22. });
  23. io.on('connection', async (socket) => {
  24. socket.join('room');
  25. // this is just for testing.
  26. setTimeout(() => {
  27. io.to('room').emit('room-event', {index: 'users', id: undefined});
  28. }, 10*1000);
  29. });
  30. app.post('/emit/:room', function (req, res) {
  31. console.log('room is :','room-' + req.params.room);
  32. console.log('message',req.body.data.title);
  33. io.to('room-' + req.params.room).emit('room-event', req.body.data.title);
  34. res.send('done');
  35. });
  36. subscriber.on("message", function (channel, message) {
  37. io.to('room').emit('server-msg', message);
  38. });
  39. server.listen(3030, () => {
  40. console.log('listening on *:3030');
  41. });
  42. subscriber.subscribe("test-channel");