2012-03-30 3 views
39

저는 node.js에 비교적 익숙하며 addons이기 때문에 아마도 초보자들입니다.Socket.io를 사용하여 클라이언트를 서버에 연결하기

웹 서버에서 간단한 HTML 페이지를 얻으려고하면 websocket.io를 사용하여 node.js를 실행하는 다른 서버에 연결하려고합니다.

클라이언트

<script src="socket.io/socket.io.js"></script> 
<script> 
    // Create SocketIO instance, connect 

    var socket = new io.Socket(); 

    socket.connect('http://127.0.0.1:8080'); 

    // Add a connect listener 
    socket.on('connect',function() { 
     console.log('Client has connected to the server!'); 
    }); 
    // Add a connect listener 
    socket.on('message',function(data) { 
     console.log('Received a message from the server!',data); 
    }); 
    // Add a disconnect listener 
    socket.on('disconnect',function() { 
     console.log('The client has disconnected!'); 
    }); 

    // Sends a message to the server via sockets 
    function sendMessageToServer(message) { 
     socket.send(message); 
    }; 
</script> 

서버 측

// Require HTTP module (to start server) and Socket.IO 
var http = require('http'); 
var io = require('socket.io'); 
var port = 8080; 

// 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>Hello Socket Lover!</h1>'); 
}); 

server.listen(port); 

// Create a Socket.IO instance, passing it our server 
var socket = io.listen(server); 

// Add a connect listener 
socket.on('connection', function(client){ 
    console.log('Connection to client established'); 

    // Success! Now listen to messages to be received 
    client.on('message',function(event){ 
     console.log('Received message from client!',event); 
    }); 

    client.on('disconnect',function(){ 
     clearInterval(interval); 
     console.log('Server has disconnected'); 
    }); 
}); 

console.log('Server running at http://127.0.0.1:' + port + '/'); 

서버가 잘 작동 시작하기 및 브라우저도 작동에 http://localhost:8080를 실행, 반환을 :

내 코드는 다음과 같습니다 예상대로 'Hello Socket Lover'. 하지만 소켓에 다른 페이지를 만들고 싶습니다. node.js에서 소켓을 실행하지 마십시오. 나는 그것을 실행할 때

는 그러나 아무 일도 발생하지 않습니다와 크롬 콘솔 반환 :

Failed to load resource   http://undefined/socket.io/1/?t=1333119551736 
Failed to load resource   http://undefined/socket.io/1/?t=1333119551735 

나는이 모든 일에있었습니다. 어떤 도움이 필요합니까?

답변

34

상대 URL이 아닌 socket.io 스크립트를로드 해 보았습니까?

당신이 사용하고 있습니다 :

<script src="socket.io/socket.io.js"></script> 

그리고 :

socket.connect('http://127.0.0.1:8080'); 

당신은 시도해야합니다 :

<script src="http://localhost:8080/socket.io/socket.io.js"></script> 

그리고 :

socket.connect('http://localhost:8080'); 

localhost:8080 스위치는 현재 설정에 맞습니다.

또한 다른 도메인의 클라이언트 페이지 (동일한 출처 정책)를로드 할 때 설치에 따라 서버와 통신하는 데 일부 문제가있을 수 있습니다. 이것은 다른 방법으로 극복 될 수 있습니다 (이 답변의 범위를 벗어남, google/SO it). 뷰/컨트롤러에서 다음

<script src="/socket.io/socket.io.js"></script> 

는 수행합니다 :

10

당신은 당신이 Socket.IO에 귀하의 링크를하기 전에 앞으로 추가 슬래시 있는지 확인해야 문제를 해결해야

var socket = io.connect() 

.

+9

'var socket = io()' –

관련 문제