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"]}
我在想什麼?爲什麼不是服務器端的東西開火?
爲什麼快遞?對於許多項目,我只需要提供1個html文件,而且對於這種情況,express僅僅是太多imo – Purefan
也許是因爲所有的socket.io教程都在其示例中使用了express? – Bobby