gpt4 book ai didi

node.js - 套接字 io 连接但不发射

转载 作者:可可西里 更新时间:2023-11-01 11:37:10 27 4
gpt4 key购买 nike

我有 socket io redis 和 express pubsub 正在进行,在我的本地主机上它工作得很好我正在使用 laravel 事件发布到 redis 然后 socket io 应该发出消息,它在本地主机上工作正常但在我的生产服务器是一个 ec2 虚拟机,它只能连接,我可以看到一条控制台消息“已连接”,但它不会发出任何事件,即使消息正在发布到 redis 这里是我的客户端和服务器

//client

<script type="text/javascript">// <![CDATA[
var socket = io.connect('http://127.0.0.1:3000/');

socket.on('connect', function(data){
//socket.emit('subscribe', {channel:'score.update'});
console.log('connected');
});

socket.on('notification.update', function (data) {
//Do something with data
console.log('Notification Caught: ', data);

});




// ]]></script>




//server
var express = require('express'),
http = require('http'),
server = http.createServer(app);

var app = express();

const redis = require('redis');
const io = require('socket.io');
const client = redis.createClient();

server.listen(3000, 'localhost');

io.listen(server).on('connection', function(client) {
const redisClient = redis.createClient()
redisClient.subscribe('notification.update');

});
redisClient.on("message", function(channel, message) {
//Channel is e.g 'score.update'
client.emit(channel, message);

});

client.on('disconnect', function() {
redisClient.quit();
});
});

最佳答案

您需要更改服务器的监听:

改变这些:

var express =   require('express'),
http = require('http'),
server = http.createServer(app);

var app = express();

const redis = require('redis');
const io = require('socket.io');
const client = redis.createClient();

server.listen(3000, 'localhost');    

io.listen(server).on('connection', function(client){
//Code
});

收件人:

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

io.on('connection, function(client){
//Code
});

server.listen(3000, function(){
console.log("Listening on :3000");
});

关于node.js - 套接字 io 连接但不发射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31229339/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com