开发者

Read complete data from stream from onMessage

How开发者_StackOverflow社区 to read event.data completely from a WebSocket using JavaScript?

onMessage: function(event) {
 var msg = event.data;
 alert(msg);
}

In the above code, the variable msg shows only the partial data. How to receive the complete data from the WebSocket server?


event.data contains the full information; it just depends on your output how much you'll see. An alert box can only contain up to a specific amount of characters, because more characters simply wouldn't fit in the alert box. alerting is not a good practice for displaying large data.

A more convenient way is to save the length and check that, e.g.:

onMessage: function(event) {
    var msg = event.data;
    alert(msg.length);
}

The length should just be the correct length, i.e. the length of the characters you sent.


WebSockets is a message based transport. If the server has broken the "stream" into several message chunks then you will receive several message events and the first message event won't have all the data that you are expecting.

Also, the WebSocket definition requires that the onmessage handler is called for full messages. You can't get partial messages (unless the browser's WebSocket implementation is broken).

I would try something asynchronous instead of alert() to log the messages you receive. For example, try console.log() if you have Firebug or the Chrome Javascript console. Are you accumulating your message data in the HTML text box or just overwriting it as you receive messages?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜