Socket.io服务器发出不激活

时间:2011-06-26 12:21:08

标签: node.js websocket socket.io

好好尝试一下NodeJS和socket.io并遇到问题。我在我的localhost上安装并运行了NodeJS和Socket.io。目前我有以下设置:

server.js

// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');

// Start the server at port 8080
var server = http.createServer(function(req, res){ 

// Send HTML headers and message
  res.writeHead(200,{ 'Content-Type': 'text/html' }); 
  res.end('<h1>NodeJS Server Online</h1>');
});
server.listen(8080);

// Create a Socket.IO instance, passing it our server
var socketserver = io.listen(server);

// Add a connect listener
socketserver.on('connection', function(socket){ 

    socket.emit("server ready");

    socket.on('test', function (msg) {
        socket.broadcast.emit('TEST:', msg);
        console.log(msg);
    });

    socket.on('user message', function (msg) {
        socket.broadcast.emit('user message', msg);
        console.log(msg);
    });

});

client.js

$(document).ready(function() {
// Stuff to do as soon as the DOM is ready;
    var socket =  io.connect('http://localhost',{port:8080});

    socket.on('server ready',function() {
        messages.append("<li>Server Ready...</li>");
        console.log("Server Ready");
    });

    // Add a connect listener
    socket.on('connect',function() {
        messages.append("<li>Connected...</li>");
        console.log("connected");
        socket.emit('test',"Just testing");
    });

});

服务器启动正常,但我的问题是server.js没有触发 socket.emit(“服务器就绪”); 行。客户端代码工作正常,如在terminal.app中测试我的服务器输出这一行:

websocket received data packet 5:::{"name":"test","args":["Just testing"]}

我错过了什么?为什么服务器端没有解雇?

1 个答案:

答案 0 :(得分:4)

我将socket.io更新为0.7.2,然后稍微修改了您的示例以使用express。下面的代码能够接收“服务器就绪”事件。

节点服务器:

var http = require('http'),  
    express = require('express');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.use(express.static(__dirname + '/public'));
});

app.listen(9000);
console.log("server started");

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

io.sockets.on('connection', function(socket){ 
    socket.emit('server ready', {msg: 'hi'}) ;
}); 

网页(/sock.html):

<html>
<body>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script> 
var socket = io.connect();
socket.on('server ready', function(data){ console.log('server ready!'); }) ;
</script> 
</body>
</html>