簡體   English   中英

node.js和javascript websockets通信

[英]node.js and javascript websockets communication

我正在嘗試使用websockets來滿足網頁與node.js的通信。 我現在已經嘗試了幾個小時,但根本不知道出了什么問題。

服務器

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);
};

有誰知道它為什么不起作用?

您在握手響應結束時錯過了最后的\\r\\n

請參閱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

一旦你得到握手工作,行socket.write("test"); 不會像你期望的那樣工作。 框架消息是框架式的,因此您需要額外的代碼來讀取和寫入消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM