1

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

3 に答える 3

0

wsの例

例を挙げました。テキストのみを処理し、テキストのサイズは64kに制限されています。

基本的に、wsは単純なソケットではありません。サーバー側でデータを解析するには、wsプロトコルに従う必要があります。

于 2012-10-21T15:52:26.610 に答える
0

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>
于 2012-10-21T12:38:49.370 に答える
0

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

        ws.onopen = function (){
            alert("Sending");
            this.send("SOME DATA !");
        }
于 2012-10-21T13:27:21.660 に答える