服务器端的Socket.io连接不起作用

时间:2013-12-24 02:38:00

标签: javascript node.js express socket.io

以下是我app.js的一部分:

var app = express();
var server = app.listen(3000);//http.createServer(app);//app.listen(3000);
var io = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
    console.log("we are in connection");
    socket.emit('entrance', {username: req.session.user});
});
server.listen(3000);

我从来没有在终端和浏览器上都收到控制台消息(这很明显) 这是我的客户方:

doctype html

html
  head
    script(type='text/javascript', src='/socket.io/socket.io.js')
    script(type='text/javascripts', src='/javascripts/jquery.js')
    script(type='text/javascripts', src='/javascripts/client.js')
    script(type='text/javascripts')
        var socket = io.connect('http://localhost')
        socket.on('entrance', function (data) {
            console.log(data);
            socket.emit('my other event', { my: 'data' })
        })

    link(rel='stylesheet', href='/stylesheets/style.css')
    title Chat Room
    body
    div#container
        ul#messages

    input(type="text",name="message",id='message_input')
    a#logout(href='/logout') Log Out

1 个答案:

答案 0 :(得分:0)

尝试用以下代码替换前三行:

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

然后保留server.listen行。