如何在浏览器和服务器之间传输数据结构 [英] How to transfer data structures between browser and server

查看:127
本文介绍了如何在浏览器和服务器之间传输数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在交互式Web应用程序的上下文中,尤其是那些利用诸如Websockets之类的技术的库,我们如何在客户端浏览器和服务器之间传输数据结构(例如,地图,列表,集合等)?到目前为止,我所遇到的示例仅传递字符串。



受支持的案例是否取决于所使用的库,还是可以使用更通用的机制?

p>

解决方案

您可以通过websocket发送三件事(从客户端的角度来看):




  • 字符串

  • ArrayBuffers

  • Blobs



如果您具有复合Javascript数据结构(映射和数组的层次结构),则应使用JSON将其序列化为字符串,然后通过WebSocket连接将它们作为字符串发送。



如果您对通过WebSocket连接发送二进制字节或文件数据感兴趣,则仍可以序列化为字符串(带宽效率低),也可以将数据作为ArrayBuffers或Blob发送。

注1:发送ArrayBuffer或Blob会在网络上生成二进制WebSocket框架,您的服务器需要支持二进制框架。



注意2:当服务器发送二进制帧时,客户端可以选择返回哪种类型的对象。这是WebSocket对象上的binaryType属性,可以将其设置为 arraybuffer或 blob。



注3:如果浏览器仅支持较旧的WebSocket Hixie协议系列(例如iOS Safari),则没有二进制数据,您只能发送和接收字符串。


In the context of interactive web apps, especially those libraries utilizing technologies such as websockets, how can we transfer data structures (e.g. maps, lists, sets, etc) between the client browser and the server? The examples I've come across so far only pass strings.

Is this supported case by case dependent on the libraries used, or a more general mechanism is available?

解决方案

You can send three things over a websocket (from the client perspective):

  • Strings
  • ArrayBuffers
  • Blobs

If you have a compound Javascript data structures (hierarchy of maps and arrays) then you should use JSON to serialize them to strings and send them over the WebSocket connection as a string.

If you are interested in sending binary byte or file data over the WebSocket connection you could still serialize to a string (inefficient bandwidth-wise) or you can send the data as ArrayBuffers or Blobs.

Note 1: When sending an ArrayBuffer or Blob results in a binary WebSocket frame on the wire your server needs to support binary frames.

Note 2: The client gets to choose what type of object is returned when the server sends a binary frame. This is the binaryType property on the WebSocket object which can be set to either "arraybuffer" or "blob".

Note 3: If you browser only supports the older WebSocket Hixie protocol series (e.g. iOS Safari) then there is no binary data and you can only send and receive strings.

这篇关于如何在浏览器和服务器之间传输数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆