大家好我在redis pub / sub中遇到问题,因为我的客户端没有显示我在redis-cli中发布的消息。我使用了stackoverflow中的代码,我做了一些修改。 Here is the link and code.我希望您能帮助我,我的目标是使用redis-cli中的redis发布将消息发布到客户端index.html。我以前做过这个,但我不能让它再次运作。先谢谢你们。
以下是我的客户index.html
<html>
<head>
<title>PubSub</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- <script src="/javascripts/socket.js"></script> -->
</head>
<body>
<div id="content"></div>
<script>
var socket = io.connect('http://localhost:3000');
var content = $('#content');
socket.on('connect', function() {
});
socket.on('message', function (message){
content.prepend(message + '<br />');
}) ;
socket.on('disconnect', function() {
console.log('disconnected');
content.html("<b>Disconnected!</b>");
});
socket.connect();
});
</script>
</body>
</html>
这是我的server.js
var express = require('express');
var app = express();
var redis = require('redis');
var http = require('http');
var server = http.createServer(app);
var socket = require('socket.io').listen(server);
var publish = redis.createClient();
app.listen(3000);
console.log("Express server listening on port 3000")
app.get('/', function (req,res) {
res.sendfile(__dirname + '/public/index.html');
});
socket.on('connection', function (client) {
var subscribe = redis.createClient();
subscribe.subscribe('pubsub');
subscribe.on("message", function (channel, message) {
publish.send(message);
});
publish.on('message', function (msg) {
});
publish.on('disconnect', function() {
subscribe.quit();
});
});
答案 0 :(得分:1)
Redis不会为您发送数据到连接的客户端。您必须指示Socket.IO发出数据:
subscribe.on("message", function (channel, message) {
socket.emit('message', message);
});