简体   繁体   English

服务器发送事件在服务器端成本

[英]Server-Sent Events costs at server side

If I understand the Server-Sent Events principle correctly, each time a client registers to an EventSource, it actually opens a new HTTP connection to the resource managing the event. 如果我正确理解了Server-Sent Events原则,那么每次客户端注册到EventSource时,它实际上都会打开一个与管理事件的资源的新HTTP连接。 Contrary to other HTTP requests, the connection stays alive so the server process/thread dedicated to this client keeps running until the client disconnects. 与其他HTTP请求相反,连接保持活动状态,因此专用于此客户端的服务器进程/线程将一直运行,直到客户端断开连接。

What if we have 1000 clients connected to an application using SSE? 如果我们有1000个客户端连接到使用SSE的应用程序怎么办? Would we have 1000 processes/threads (doing the same thing) running concurrently just to handle the SSEs? 我们是否有1000个进程/线程(做同样的事情)同时运行只是为了处理SSE? I guess I'm wrong but if I'm not, is it really more efficient than the usual AJAX polling method where at least the server doesn't need to run that many processes/threads concurrently? 我想我错了,但如果我不是,它是否真的比通常的AJAX轮询方法更有效率,至少服务器不需要同时运行那么多进程/线程?

Yes, each client keeps the connection open as long as it can. 是的,每个客户端尽可能保持连接打开。 With 1000 concurrent users you'd have 1000 TCP/IP connections open. 拥有1000个并发用户,您将打开1000个TCP / IP连接。

However, whether each connection uses a thread depends on the server. 但是,每个连接是否使用线程取决于服务器。

Apache typically keeps a thread running for each connection, so it's pretty expensive. Apache通常会为每个连接保持一个线程运行,因此它非常昂贵。 With Apache it's best to disable KeepAlive and use polling. 使用Apache,最好禁用KeepAlive并使用轮询。

OTOH with event-based servers like node.js you can have just one process that manages all connections, so cost of each connection is much lower and you should be able to keep thousands of connections open easily. OTOH使用基于事件的服务器(如node.js),您只需要一个管理所有连接的进程,因此每个连接的成本要低得多,您应该能够轻松地保持数千个连接的打开。

The cool thing about SSE is that you can use it to do polling as well. 关于SSE的一个很酷的事情是你也可以使用它进行轮询。 It has retry: directive that specifies how long client should wait before reconnecting (polling) again. 它有retry:指令,指定客户端在重新连接(轮询)之前应该等待多长时间。 Just send that and close the connection when you want polling. 只需发送它并在需要轮询时关闭连接。

It depends on the threading model of the server. 这取决于服务器的线程模型。 Apache defaults to one thread (or process) per connection so, even if the threads aren't doing very much (as is expected with an SSE connections), they sit there using up resources. Apache默认为每个连接一个线程(或进程),因此,即使线程没有做很多事情(如SSE连接所预期的那样),它们也会使用资源。

Servers like Nginx have a slightly different model, each thread handles multiple requests asynchronously. Nginx这样的服务器有一个稍微不同的模型,每个线程异步处理多个请求。 So stuff like SSE and WebSockets is far more efficient. 所以像SSE和WebSockets这样的东西效率更高。

Apache can be made to perform more like Nginx and similar servers. 可以使Apache 更像Nginx和类似的服务器。

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

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