2012-10-04 4 views
1

websocket을 사용하여 node.js와 통신하기 위해 만난 웹 페이지를 얻으려고합니다. 나는 지금 몇 시간 동안 노력해 왔지만 무엇이 잘못 될지 간단히 알지 못합니다.node.js와 javascript websockets communication

서버

var net = require('net'); 

var server = net.createServer(function (socket) { 

    var handsShaked=false; 

    socket.on('data', function(data) { 
     if(!handsShaked){ 
      data=(data+"").split("\r").join("").split("\n"); 
      var key=null; 
      for(i in data){ 
       if(data[i].indexOf("Sec-WebSocket-Key:")===0) 
        key=data[i].split(":")[1].split(" ").join(""); 
      } 

      var magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; 
      var sha = sha1(key+magic); 
      var accept = new Buffer(sha).toString('base64'); 

      socket.write(
       "HTTP/1.1 101 Switching Protocols\r\n"+ 
       "Upgrade: websocket\r\n"+ 
       "Connection: Upgrade\r\n"+ 
       "Sec-WebSocket-Accept: "+accept+"\r\n" 
      ); 

      handsShaked=true; 
     } 

     socket.write("test"); 
    }); 
}); 

server.listen(10666); 

가 작동하지 않는 이유

socket = new WebSocket("ws://localhost:10666"); 
socket.onopen=function(){ 
    console.log('open'); 
    socket.send('Dit is een test'); 
} 
socket.onmessage=function(msg){ 
    console.log('msg'); 
    alert(msg); 
} 
socket.onerror = function (error) { 
    console.log('error'); 
    alert('WebSocket Error ' + error); 
}; 

사람이 알고있는 클라이언트?

+0

오류를 찾으셨습니까? 콘솔에 무엇이 나타 납니까? – MrOBrian

+0

오류가 없습니다. 소켓이 열리 며 node.js에서 분리로 인해 사용자가 로그 아웃 할 수 있습니다. 클라이언트 측 이벤트가 트리거되지 않습니다. – user6

답변

4

당신은 HTTP rfc2616

Response  = Status-Line    ; Section 6.1 
        *((general-header  ; Section 4.5 
        | response-header  ; Section 6.2 
        | entity-header) CRLF) ; Section 7.1 
        CRLF 
        [ message-body ]   ; Section 7.2 

귀하의 코드는 응답 후 CRLF 누락을 참조하여 핸드 셰이크 응답

의 끝에 최종 \r\n을 놓치고있어.

핸드 셰이크가 작동하면 socket.write("test"); 줄이 예상대로 작동하지 않습니다. Websocket 메시지는 framed이므로 메시지를 읽고 쓰는 데 추가 코드가 필요합니다.