Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

node.js - socket.io not emit from redis client event

Please, help. I'm listening when redis client publish some data and then try to emit the data with socket.io but got the error:

chat.sockets.emit('tickets',{
    ^
TypeError: chat.sockets.emit is not a function

The client connects, console log shows "a user connected", after that node.js server crashes on the line "chat.sockets.emit('tickets',{"

const http = require('http');
const express = require('express');
const socketIo = require('socket.io');
const redis = require('redis');
const client = redis.createClient({
    host: '127.0.0.1',
    port: 6379
});
const client2 = redis.createClient({
    host: '127.0.0.1',
    port: 6379
});
var app = express();
app.use((req, res, next) => { res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Header","Origin, X-Requested-With, Content-Type, Accept");
    res.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS");
    next();
});
const port = process.env.PORT || 3001;
var server = http.createServer(app);
var io = socketIo(server, {cors: {
    origin: "http://localhost",
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true 
}});
var chat=io.of('/sock');
server.listen(port, (req,res) => { console.log("Server is up on ", port);  }); 
chat.use((socket, next) => {
  if (socket.handshake.query && socket.handshake.query.user){    
        client2.exists(('site_point:' + socket.handshake.query.user), (err, ok) => {
          if (err) throw err;
          if(ok){
                next();
            }else {
                next(new Error('Authentication error'));
            }
        });
  }else {
    next(new Error('Authentication error'));
  }
})
.on('connection', (socket) => {
    console.log('a user connected');
    socket.emit('hello',{
        message : 'Hello World',id: socket.id
    });
});
client.on('message', (channel, key)  => {
    let jsonP = JSON.parse(key);
    chat.sockets.emit('tickets',{
      message : jsonP
    });
});
client.subscribe("mysite:mc");
question from:https://stackoverflow.com/questions/65944478/socket-io-not-emit-from-redis-client-event

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...