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
How do I tell the type of websocket onmessage's parameter?
提问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.binaryType
allows you to define in which format you'd like to obtain the binary data.
服务器可以发送的适当的两种类型的帧是文本帧和二进制帧(5.2)。将ws.binaryType
允许您定义以哪种方式,你想获得的二进制数据。
- Binary data: depending on
binaryType
being set to eitherarraybuffer
orblob
- Text data: string
- 二进制数据:取决于
binaryType
设置为arraybuffer
或blob
- 文本数据:字符串
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"
参考:
4. If typeindicates that the data is Text, then initialize event's
data
attribute to data.If typeindicates that the data is Binary, and
binaryType
is set to "blob
", then initialize event'sdata
attribute to a newBlob
object that represents dataas its raw data.If type indicates that the data is Binary, and
binaryType
is set to "arraybuffer
", then initialize event'sdata
attribute to a new read-onlyArrayBuffer
object whose contents aredata
.
4.如果type表示数据为Text,则将event的
data
属性初始化为data。如果type指示数据是 Binary 并且
binaryType
设置为“blob
”,则将event的data
属性初始化为一个新Blob
对象,该对象将数据表示为其原始数据。如果 type 指示数据是 Binary,并
binaryType
设置为“arraybuffer
”,则将event的data
属性初始化为一个新的只读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.data
is string
. If binary data is sent, then e.data
will be an instance of either ArrayBuffer
, or Blob
, depending on the value of the ws.binaryType
property set by the receiver.
websocket 帧中的数据类型由发送方决定(参见1.2),因此不能由接收方设置。如果发送文本数据,则类型e.data
为string
。如果二进制数据被发送,然后e.data
将二者之一的一个实例ArrayBuffer
,或者Blob
,取决于的值ws.binaryType
由接收机属性集。
"Or how do I know which type I get?"
“或者我怎么知道我得到的是哪种类型?”
This has already been answered by pimvdb.
pimvdb 已经回答了这个问题。