javascript 如何判断 websocket onmessage 参数的类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9462879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:44:27  来源:igfitidea点击:

How do I tell the type of websocket onmessage's parameter?

javascriptwebsocketblobarraybuffer

提问by marc40000

Here https://developer.mozilla.org/en/WebSockets/WebSockets_reference/MessageEventit states attribute data is of type DOMString| Blob | ArrayBuffer. How do I tell it which type I want? Or how do I know which type I get?

这里https://developer.mozilla.org/en/WebSockets/WebSockets_reference/MessageEvent它声明属性数据的类型为 DOMString| 斑点| 数组缓冲区。我如何告诉它我想要哪种类型?或者我怎么知道我得到的是哪种类型?

回答by pimvdb

The appropriate two types of frames that a server can send are text frames and binary frames (5.2). The ws.binaryTypeallows you to define in which format you'd like to obtain the binary data.

服务器可以发送的适当的两种类型的帧是文本帧和二进制帧(5.2)。将ws.binaryType允许您定义以哪种方式,你想获得的二进制数据。

  • Binary data: depending on binaryTypebeing set to either arraybufferor blob
  • Text data: string
  • 二进制数据:取决于binaryType设置为arraybufferblob
  • 文本数据:字符串

To determine the type, you can use:

要确定类型,您可以使用:

  • e.data instanceof ArrayBuffer
  • e.data instanceof Blob
  • typeof e.data === "string"
  • e.data instanceof ArrayBuffer
  • e.data instanceof Blob
  • typeof e.data === "string"

Reference:

参考

4. If typeindicates that the data is Text, then initialize event's dataattribute to data.

If typeindicates that the data is Binary, and binaryTypeis set to "blob", then initialize event's dataattribute to a new Blobobject that represents dataas its raw data.

If type indicates that the data is Binary, and binaryTypeis set to "arraybuffer", then initialize event's dataattribute to a new read-only ArrayBufferobject whose contents are data.

4.如果type表示数据为Text,则将eventdata属性初始化为data

如果type指示数据是 Binary 并且binaryType设置为“ blob”,则将eventdata属性初始化为一个新Blob对象,该对象将数据表示为其原始数据。

如果 type 指示数据是 Binary,并binaryType设置为“ arraybuffer”,则将eventdata属性初始化为一个新的只读ArrayBuffer对象,其内容为data

回答by Chris

"How do I tell it which type I want?"

“我怎么告诉它我想要哪种类型?”

The type of the data in a websocket frame is determined by the sender (see 1.2) and hence cannot be set by the receiver. If textual data is sent, then the type of e.datais string. If binary data is sent, then e.datawill be an instance of either ArrayBuffer, or Blob, depending on the value of the ws.binaryTypeproperty set by the receiver.

websocket 帧中的数据类型由发送方决定(参见1.2),因此不能由接收方设置。如果发送文本数据,则类型e.datastring。如果二进制数据被发送,然后e.data将二者之一的一个实例ArrayBuffer,或者Blob,取决于的值ws.binaryType由接收机属性集。

"Or how do I know which type I get?"

“或者我怎么知道我得到的是哪种类型?”

This has already been answered by pimvdb.

pimvdb 已经回答了这个问题。