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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…