2012-11-04 8 views
0

저는 node.js와 socket.io를 처음 사용하고 서버를 클라이언트에 연결하려고 시도했습니다 (예제 : http://socket.io/#how-to-use). (더 로컬 호스트 없음)Node.js + socket.io : 서버의 앱이 제대로 작동하지 않습니다.

가 서버 :

var app = require('http').createServer(handler) 
    , io = require('socket.io').listen(app) 
    , fs = require('fs') 

app.listen(80); 

function handler (req, res) { 
    fs.readFile(__dirname + '/index.html', 
    function (err, data) { 
    if (err) { 
     res.writeHead(500); 
     return res.end('Error loading index.html'+err); 
    } 

    res.writeHead(200); 
    res.end(data); 
    }); 
} 

io.sockets.on('connection', function (socket) { 
    socket.on('message', function(msg){ 
     console.log('Got text: '+msg); 
     socket.broadcast.send(msg); 
    }); 
    socket.on('disconnect', function() { }); 
}); 

클라이언트 :

<html><head><script src="/socket.io/socket.io.js"></script> 
<script> 
    var socket = io.connect(); 
    socket.on('connect', function() { 
    alert('connected.'); 

    socket.on('message', function (msg) { 
     // my msg 
     alert('message received: '+msg); 
    }); 
    socket.send('hi'); 

    }); 


</script> 
</head><body>This is the content :)</body> 
</html> 
가 콘솔에서

구글 크롬 표시 : 또한

Unexpected response code: 502 

, 모든 메시지를받은 후, 크롬

추가
GET http://[myServer]/socket.io/1/?t=1352313105809 socket.io.js:1659 
Socket.handshake socket.io.js:1659 
Socket.connect socket.io.js:1699 
maybeReconnect 

콘솔. Wheres 문제가 있습니까?

답변

3

How-To 페이지의 예제는 모두 웹 사이트를 제공하는 데 일반적으로 사용되는 포트 80을 사용합니다.

그러나 예제에서는 포트 8080을 사용합니다.

socket.io 스크립트가로드되는 경우 웹 브라우저의 콘솔을 확인하십시오. 위의 작동하지 않는, 웹 서버가 실행되는 어떤 포트에 몇 가지 통찰력을 공유하십시오 당신은 http://localhost:8080/socket.io/socket.io.js로 명시 적 URL을 제공하고 io.connect('http://localhost:8080');

에 연결해야 할 수 있습니다.


(업데이트 된) 예에서는 서버 측에서 수신 메시지를 실제로 처리하는 코드가 없습니다.

`socket.on('message', function(msg){ 
    console.log('Got text: '+msg); 
    socket.send(msg); 
}); 

적어도 메시지를 클라이언트로 다시 보내야합니다. 즉, 알림은 클라이언트가 메시지를받을 때만 트리거됩니다. node.js 콘솔에서 들어오는 메시지 나 보낸 메시지를 출력합니까? 연결시 몇 줄의 node.js 콘솔이 다음과 같이 표시됩니다.

debug - client authorized 
info - handshake authorized ... 
debug - setting request GET /socket.io/1/... 
debug - set heartbeat interval for client ... 
debug - client authorized for 
debug - websocket writing 1:: 
debug - sending data ack packet 
+0

감사합니다. 코드를 편집하고 연결 했으므로 스크립트 (socket.io.js)가로드 된 것 같습니다. 그러나 아무런 메시지도받지 못했습니다. 메시지가 실제로 전송되는지 테스트 할 수있는 방법이 있습니까? – xoxox

+0

@ xoxox 내 답변을 업데이트했습니다. – mabako

+0

감사합니다. 마침내 자체 메시지를 받지만 다른 메시지는 수신하지 않습니다 (다른 브라우저로 연결할 때). Opera는 콘솔에 아무것도 인쇄하지 않습니다. Google 크롬은 "예기치 않은 응답 코드 : 502"를 인쇄하지만 여전히 작동합니다. (질문을 편집하고 정보를 추가했습니다.) – xoxox

관련 문제