Communication delay in HTML5 websocket with nodejs

Hi everyone and thanks for reading this. I'm using NodeJS with WS module on server side and HTML5 WebSocket API in Firefox on client side. The operating system is windows 7 64 bit. Whenever I make a connection from the client to server, the connection forms instantaneously, but when I send some data there is a huge delay. Sometimes the messages seem to reach the server instantly, other times they reach after some seconds and even minutes and most of the time they fail to reach the server at all. I'm attaching the code from both client and server sides. If someone can help me, I'd be really thankful.

Client Side Code

<!doctype html>
<html>
    <head>
        <script>
            var ws = new WebSocket("ws://localhost:5225");
            ws.onopen = function (){
                alert("Sending");
                ws.send("SOME DATA !");
            }
        </script>
    </head>
    <body>
    </body>
</html>

Server Side Code

var WebSocketServer = require('./ws').Server;
var wss = new WebSocketServer({port:5225});
var ws;

wss.on('connection',function (wsock){
    console.log("Connection Recieved");

    ws = wsock;

    ws.on('message',onnMessage);

    ws.on('close',onnClose);
});

function onnMessage(data){
        console.log("Data Recieved : "+data);
}

function onnClose(){
        console.log("Connection closed");
}

I am unable to test at the moment, but I believe the issue is your websocket variable(ws) is out of scope inside the .onopen() event or the variable is being freed by the garbage collector before the event fires. To fix this, create the socket as a global(or to an object in the global scope):

<script>
    window.ws = new WebSocket("ws://localhost:5225");
    ws.onopen = function (){
        alert("Sending");
        ws.send("SOME DATA !");
    }
</script>

To access the ws object inside the onopen handler use the this reference, like so:

        ws.onopen = function (){
            alert("Sending");
            this.send("SOME DATA !");
        }

ws example

I made an example. It handles only text and the size of the text is limited to 64k.

Basically, ws is not a simple socket. You need to follow the ws protocal to parse the data in the server side.