Node.js + Express.js + Socket.io

时间:2014-02-20 19:05:05

标签: javascript node.js express socket.io

无论如何都不起作用,我真的尝试了很多不同的方式,但没有任何作用.. 我想与socket.io建立实时连接,以监视redis数据库以获取列表中的每个新添加项。 有什么想法吗?

app.js

/**
 * Module dependencies.
 */

var express = require('express');
var http = require('http');
var path = require('path');
var crawler = require('crawler.js');


var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
//app.use(express.errorHandler());
}
 app.get('/rootaccess',function(req, res){
res.render('crawlercontrol');
});
app.get('/crawler/monitor',function(req, res){
res.render('monitor');
});
app.get('/crawler/start',function(req,res){
crawler.start(res);
});

app.get('/crawler/stop',function(req,res){
crawler.stop(res);
});


http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

var io = require('socket.io').listen(app.listen(3111));

io.sockets.on('connection', function (socket) {
    console.log('hei socket.io');
    socket.emit('message', { message: 'welcome to the chat' });
    socket.on('send', function (data) {
        io.sockets.emit('message', data);
    });
});

的index.html

<!DOCTYPE html>
<html>
    <head>
        <title>ROOT Monitor</title>
        <link rel="stylesheet" href="/css/normalize.css">
        <link rel="stylesheet" href="/css/foundation.css" />
    <link rel="stylesheet" href="/css/font-awesome.min.css">
    <script src="/js/libs/modernizr.js"></script>
    </head>
<body>
<div id="monitor">
    Monitor
</div>
</body>
<script src="/js/libs/jquery-1.10.2.js"></script>
<script src="/js/libs/foundation.min.js"></script>
<script src='/socket.io/socket.io.js' />
<script>
    var socket = io.connect('http://localhost:3111');
    socket.on('news', function (data) {
    console.log(data);
    });
</script>
</script>
</html>

此时出现的唯一错误是socket.io没有为客户端提供socket.io.js ..

1 个答案:

答案 0 :(得分:0)

我不知道这是不是;这只是一种预感。在app.js中,您告诉快递应用监听app对象中指定的端口:

http.createServer(app).listen(app.get('port'), ...

但是当您创建io时,您会在对象app.listen()的{​​{1}}方法中再次致电listen

require

我的预感是,也许你强迫var io = require('socket.io').listen(app.listen(3111)); 服务器听两次可能导致问题,再次只是预感。如果我错了告诉我。如果你真的想听3111端口,你可以试试这个:

app

看看是否能让你随处可见。