2011-06-26 113 views
3

好的,試着在NodeJS和socket.io上運行並遇到問題。我在本地主機上安裝並運行了NodeJS和Socket.io。目前我有以下設置: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"]} 

我在想什麼?爲什麼不是服務器端的東西開火?

回答

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> 
+0

爲什麼快遞?對於許多項目,我只需要提供1個html文件,而且對於這種情況,express僅僅是太多imo – Purefan

+0

也許是因爲所有的socket.io教程都在其示例中使用了express? – Bobby