[英]Nodejs simple socket.io example not working
我有以下服務器端代碼:
var express = require('express')
, http = require('http')
, routes = require('./routes')
, io = require('socket.io')
, factory = require('./serverfactory.js');
var app = express();
var server = app.listen(3000);
io = io.listen(server);
io.sockets.on('connection',function(socket){
console.log('new user');
socket.emit('hail','mysimplemsg');
socket.on('customevent',function(msg){
console.log(msg);
});
});
//var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', routes.index);
這是客戶端:
var socket = io.connect('http://localhost:3000');
socket.emit('customevent','work');
socket.on('hail',function(msg){
console.log(msg);
});
我期望我的git console
輸出new user
(確實如此),然后它應該輸出work
(事實並非如此),然后在瀏覽器控制台mysimplemsg
得到一個味精(事實並非如此)。
這是怎么回事,為什么不調用customevent
服務器端事件以及為什么不調用hail
的客戶端事件?
我相信問題在於, 在連接之前,您正在從客戶端發出customevent 。 嘗試添加一個連接處理程序,並將客戶端發出的內容移入其中:
var socket = io.connect('http://localhost:3000');
socket.on('hail',function(msg){
console.log(msg);
});
socket.on('connect',function(){
console.log('connected to socket.io server');
socket.emit('customevent','work');
});
如果未點擊連接處理程序,請驗證您是否正確引用了客戶端socket.io javascript庫(Jade語法):
script(type='text/javascript',src='/socket.io/socket.io.js')
終於想通了。
它在opera
上運行良好,但在chrome and firefox
。 我發現此鏈接中的家伙說要在服務器端插入此代碼段。
io.configure('development', function(){
io.set('transports', ['xhr-polling']);
});
現在工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.