1

I'm trying to get met webpage to communicate with node.js using websockets. I've been trying for several hours now but simply don't know what is going wrong.

server

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

client

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

anyone knows why it is not working?

2
  • do you get any errors? what shows up in your console? Commented Oct 4, 2012 at 22:42
  • No errors. The socket will be opened and in node.js i can logwhen the user leaves because of the disconnection. None of the client side events is ever triggered. Commented Oct 5, 2012 at 5:48

1 Answer 1

4

You're missing a final \r\n at the end of your handshake response

See the 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

Your code is missing the CRLF after the response.

Once you get the handshake working, the line socket.write("test"); won't work as you expect. Websocket messages are framed so you'll need additional code to read and write messages.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.