使用 WebSockets... 有效吗? [英] Using WebSockets... Efficiently?

查看:75
本文介绍了使用 WebSockets... 有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几乎所有可以在 WebSockets 上找到的指南和教程,但没有一个涵盖了如何有效地使用它们.

I've read pretty much every guide and tutorial I can find on WebSockets, but not one of them has covered how to use them efficiently.

有没有人有任何关于如何做到这一点的指南?我担心单个连接可以占用的带宽量,尤其是当应用程序打开了数百个连接时.

Does anyone have any sort of guide on how to do this? I'm concerned about the amount of bandwidth a single connection can take up, especially when applications have hundrends of connections opened.

推荐答案

WebSocket 的效率取决于处理它们的网络服务器的实现和架构.与所有不同的 HTTP 标头字段相比,WebSocket 是一种非常高效的协议,只有 2 个字节 (!) 的开销 和在每个 Ajax 请求中发送的 HTTP cookie.

The efficiency in WebSocket depends on the implementation and architecture of the webserver that handles them. WebSocket is a very efficient protocol with only 2 byte (!) overhead, compare to the all different HTTP header fields and HTTP cookies that is sent in every Ajax request.

通常一个高效的 websockets 网络服务器应该是事件驱动的(见下面的例子).相反,实现 Web 服务器的传统方法是为每个请求生成一个新线程.但是线程分配了很多内存,例如每个线程 256MB.因此,如果服务器上有 1GB 内存,则无法同时处理大量请求.但是如果您的服务器是事件驱动的,您的内存使用量将几乎保持不变,因为不会创建新线程.另请参阅 从技术上讲,为什么 Erlang 中的进程更高效比操作系统线程?

Usually an efficient webserver for websockets should be event driven (see the examples below). In opposite, the traditional way to implement web servers have been to spawn a new thread per request. But threads allocate much memory e.g. 256MB per thread. So if you have 1GB memory on your server you can't handle very many requests concurrently. But if your server is event-driven your memory usage will be almost constant, since new threads aren't created. See also Technically why is processes in Erlang more efficient than OS threads?

您可以在 WebSocket 中发送任何数据.如果客户端是 Web 浏览器,或者 类型化数组,则 JSON 是有效的.如果您的客户端是自定义应用程序,您可以使用协议缓冲区.另请参阅 Google Wave 客户端-服务器协议白皮书

You can send any data in your WebSockets. JSON is efficient if the client is a web browser, or maybe typed arrays. If your client is a custom application, you can use Protocol Buffers. See also Google Wave Client-Server Protocol Whitepaper

您可以使用 Twisted (Python) 或 Netty (Java).Play Framework 是在 Netty 上实现的适用于 Java 和 Scala 的高效 Web 框架.另一个有效的替代方案是 Yaws 网络服务器 (Erlang) 或 Node.js + Socket.io (JavaScript).

You can implement efficient websocket servers using Twisted (Python) or Netty (Java). Play Framework is an efficient web framework for Java and Scala implemented on Netty. Another efficient alternative is Yaws web server (Erlang) or Node.js + Socket.io (JavaScript).

作为应用程序开发人员,您发送的数据越少,效率越高(流量越少),服务器上的负载也就越少.

As an application developer, the less data you send the more efficient (less traffic) and the less load on your server.

这篇关于使用 WebSockets... 有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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