简体   繁体   English

从onMessage读取流中的完整数据

[英]Read complete data from stream from onMessage

How to read event.data completely from a WebSocket using JavaScript? 如何使用JavaScript从WebSocket完全读取event.data

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

In the above code, the variable msg shows only the partial data. 在上面的代码中,变量msg仅显示部分数据。 How to receive the complete data from the WebSocket server? 如何从WebSocket服务器接收完整的数据?

event.data contains the full information; event.data包含完整信息; 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. 警报框最多只能包含特定数量的字符,因为更多的字符根本无法容纳在警报框中。 alert ing is not a good practice for displaying large data. alert不是显示大数据的好习惯。

A more convenient way is to save the length and check that, eg: 一种更方便的方法是保存长度并检查,例如:

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

The length should just be the correct length, ie the length of the characters you sent. 该长度应为正确的长度,即您发送的字符的长度。

WebSockets is a message based transport. WebSockets是基于消息的传输。 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. 同样,WebSocket定义要求onmessage处理程序被调用以获取完整消息。 You can't get partial messages (unless the browser's WebSocket implementation is broken). 您无法获得部分消息(除非浏览器的WebSocket实现被破坏)。

I would try something asynchronous instead of alert() to log the messages you receive. 我会尝试使用异步方法而不是alert()来记录您收到的消息。 For example, try console.log() if you have Firebug or the Chrome Javascript console. 例如,如果您具有Firebug或Chrome Javascript控制台,请尝试console.log()。 Are you accumulating your message data in the HTML text box or just overwriting it as you receive messages? 您是在HTML文本框中累积消息数据还是在接收消息时将其覆盖?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM