2013-07-18 4 views
2

Я новичок в узле js и socket.io, я пробую базовый пример socket.io в моей машине Windows.Ошибка подключения от клиента к серверу в socket.io

код сервера

var io = require('socket.io').listen(8080); 

io.sockets.on('connection', function (socket) { 
    socket.emit('news', { hello: 'world' }); 
    socket.on('my other event', function (data) { 
    console.log(data); 
    }); 
}); 

Client Code

<script src="http://localhost:8080/socket.io/socket.io.js"></script> 
<script> 
    var socket = io.connect('http://localhost:8080/'); 

    socket.on('news', function (data) { 
    console.log(data); 
    socket.emit('my other event', { my: 'data' }); 
    }); 
    socket.on('connect', function() { 
     alert('connect'); 
    }); 

    socket.on('error', function (data) { 
     console.log(data || 'error'); 
    }); 

    socket.on('connect_failed', function (data) { 
     console.log(data || 'connect_failed'); 
    }); 
</script> 

В вышеприведенном клиента сценария не может подключиться к серверу (в консоли connect_failed был зарегистрирован), но в то же время была показана следующая сторона сервера,

info - socket.io started 
    debug - served static content /socket.io.js 
    debug - client authorized 
    info - handshake authorized ALB0omsm3E2ZvPMn02x7 
    debug - setting request GET /socket.io/1/websocket/ALB0omsm3E2ZvPMn02x7 
    debug - set heartbeat interval for client ALB0omsm3E2ZvPMn02x7 
    debug - client authorized for 
    debug - websocket writing 1:: 
    debug - websocket writing 5:::{"name":"news","args":[{"hello":"world"}]} 
    debug - setting request GET /socket.io/1/xhr-polling/ALB0omsm3E2ZvPMn02x7?t=1 
374168523063 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - cleared heartbeat interval for client ALB0omsm3E2ZvPMn02x7 
    debug - setting request GET /socket.io/1/jsonp-polling/ALB0omsm3E2ZvPMn02x7?t 
=1374168533064&i=0 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - clearing poll timeout 
    debug - clearing poll timeout 
    debug - jsonppolling writing io.j[0]("8::"); 
    debug - set close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - jsonppolling closed due to exceeded duration 
    debug - setting request GET /socket.io/1/jsonp-polling/ALB0omsm3E2ZvPMn02x7?t 
=1374168556555&i=0 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - cleared close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - clearing poll timeout 
    debug - jsonppolling writing io.j[0]("8::"); 
    debug - set close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - jsonppolling closed due to exceeded duration 
    debug - setting request GET /socket.io/1/jsonp-polling/ALB0omsm3E2ZvPMn02x7?t 
=1374168576586&i=0 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - cleared close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - clearing poll timeout 
    debug - jsonppolling writing io.j[0]("8::"); 
    debug - set close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - jsonppolling closed due to exceeded duration 
    debug - setting request GET /socket.io/1/jsonp-polling/ALB0omsm3E2ZvPMn02x7?t 
=1374168596600&i=0 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - cleared close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - clearing poll timeout 
    debug - jsonppolling writing io.j[0]("8::"); 
    debug - set close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - jsonppolling closed due to exceeded duration 
    debug - setting request GET /socket.io/1/jsonp-polling/ALB0omsm3E2ZvPMn02x7?t 
=1374168616640&i=0 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - cleared close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - clearing poll timeout 
    debug - jsonppolling writing io.j[0]("8::"); 
    debug - set close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - jsonppolling closed due to exceeded duration 
    debug - setting request GET /socket.io/1/jsonp-polling/ALB0omsm3E2ZvPMn02x7?t 
=1374168636656&i=0 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - cleared close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - setting request GET /socket.io/1/xhr-polling/ALB0omsm3E2ZvPMn02x7?t=1 
374168523063 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - clearing poll timeout 
    debug - clearing poll timeout 
    debug - xhr-polling writing 8:: 
    debug - set close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - xhr-polling closed due to exceeded duration 
    debug - setting request GET /socket.io/1/xhr-polling/ALB0omsm3E2ZvPMn02x7?t=1 
374168663072 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - cleared close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - clearing poll timeout 
    debug - xhr-polling writing 8:: 
    debug - set close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - xhr-polling closed due to exceeded duration 
    debug - setting request GET /socket.io/1/xhr-polling/ALB0omsm3E2ZvPMn02x7?t=1 
374168690890 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - cleared close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - clearing poll timeout 
    debug - xhr-polling writing 8:: 
    debug - set close timeout for client ALB0omsm3E2ZvPMn02x7 
    debug - xhr-polling closed due to exceeded duration 
    debug - setting request GET /socket.io/1/xhr-polling/ALB0omsm3E2ZvPMn02x7?t=1 
374168710895 
    debug - setting poll timeout 
    debug - discarding transport 
    debug - cleared close timeout for client ALB0omsm3E2ZvPMn02x7 

Как я могу исправить ошибку в приведенных выше сценариях, чтобы успешно запустить базовый пример socket.io?

ответ

5

Вы можете настроить параметры socket.io в соответствии с вашими требованиями. https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO

Я также столкнулся с той же проблемой и обнаружили, что добавление ниже линии решает проблему

io.set('transports',['xhr-polling']); 
+2

Да @varun. Почему websockets не работают? – Hackableweb

+0

Привет. Эта строка кода спасает мою жизнь. Интересно, почему это работает. Спасибо! – ZillGate

+0

@ZillGate: Рад помочь :) – softvar

0

Сделать localhost.js файл с этими данными:

var port = 80, 
http = require('http'), 
fs = require('fs'), 
socket = require('socket.io'), 
app = function (req, res) { 
    var url = req.url == '/' ? '/index.html' : req.url; 
    fs.readFile(__dirname + url, 'utf8', function (err, data) { 
    if (err) return console.log(err); 
    res.end(data); 
    }); 
}, 
httpServer = http.createServer(app).listen(port), 
io = socket.listen(httpServer); 
io.sockets.on('connection', function (socket) { 
    socket.emit('news', { hello: 'world' }); 
    socket.on('my other event', function (data) { 
    console.log(data); 
    }); 
}); 

и файл index.html с этим:

<html> 
<head> 
    <script src="socket.min.js"></script> 
</head> 
<body> 
<script> 
    var socket = io.connect('ws://localhost:80/'); 
    socket.on('news', function (data) { 
    console.log(data); 
    socket.emit('my other event', { my: 'data' }); 
    }); 

    socket.on('connect', function() { 
    console.log('connect'); 
    }); 

    socket.on('error', function (data) { 
    console.log(data || 'error'); 
    }); 
</script> 
</body> 
</html> 

пут socket.min.js в той же папке, а затем запустить в cmd:

node localhost.js 
+0

Не работает @rafaelcastrocouto. Та же проблема. – Hackableweb

+0

он работает для меня ... im running nodejs на окнах 7. Возможно, вам нужно переустановить/обновить nodejs и socket.io. – rafaelcastrocouto

+1

после изменения типа транспорта на xhr, теперь работающего на моем хроме и firefox :). Зачем? – Hackableweb

Смежные вопросы