大家好我想知道我的代码中有什么错误,我的代码是关于socket.io和redis pub / sub这是我第一次尝试这个,希望你能帮助我们。
这是我的 index.html
<!doctype html>
<html>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = new io.Socket();
socket.connect();
socket.on('connection', function (socket) {
console.log('Connected');
});
socket.on('disconnect', function (socket) {
console.log('Disconnected');
});
</script>
<center>
<h1>Test Page</h1>
</center>
</html>
这是我的 app.js
var redis = require('redis');
var app = require('http').createServer();
var io = require('socket.io').listen(app);
var client = redis.createClient();
var pub = redis.createClient();
var sub = redis.createClient();
app.listen(1234);
io.sockets.on('connection', function (socket){
sub.on('subscribe', function (channel){
pub.publish('Pub','Test Message 1');
pub.publish('Pub','Test Message 2');
pub.publish('Pub','Test Message 3');
});
sub.on('message', function (channel, message) {
console.log(channel + ':' + message);
sub.unsubscribe();
pub.end();
sub.end();
});
sub.incr('Channel Test');
sub.incr('Pub');
});
我希望你能帮我解决这个问题。先谢谢你们。
答案 0 :(得分:3)
我可以在您的代码中看到许多错误:
http://localhost:1234/
,因为它是在您的服务器代码中定义的。
app中没有使用var client
sub
永远不会订阅某些内容。您需要订阅频道subscriber mode
中的连接无法向redis发送命令:只有修改订阅集的命令才有效sub.incr
永远不会发布消息:您必须调用publish。pub.end()
或sub.end()
,因为该连接将会关闭。message
:内存泄漏我不知道你想做什么,但这里有更新版本:
<强>的index.html 强>
<!doctype html>
<html>
<script src="http://localhost:1234/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:1234/');
socket.on('connection', function (socket) {
console.log('Connected');
});
socket.on('disconnect', function (socket) {
console.log('Disconnected');
});
</script>
<center>
<h1>Test Page</h1>
</center>
</html>
<强> app.js 强>
var redis = require('redis');
var app = require('http').createServer();
var io = require('socket.io').listen(app);
var pub = redis.createClient();
var sub = redis.createClient();
app.listen(1234);
sub.subscribe('Pub');//subscribe to Pub channel
sub.on('message', function (channel, message) {
console.log(channel + ':' + message);
});
io.sockets.on('connection', function (socket) {
pub.publish('Pub', 'New Connection');
pub.incr('Channel Test'); //increment 'Channel Test' but do not publish messages
pub.incr('Pub'); //increment 'Pub' but do not publish messages
});
答案 1 :(得分:1)
我没有看到你在socket.io服务器中将redis设置为store。我做的一些例子供您参考:
// start up express server along with socket.io
var express = require('express');
var server = express();
var socket = require('socket.io');
var io = socket.listen(server);
// socket.io
io.set('store', new socket.RedisStore);
// set-up connections...
io.sockets.on('connection', function(socket) {
io.emit('an event sent to all connected clients');
socket.on('some-event', function(rooms) {
...
});
});
您可以阅读以下文档链接: