简体   繁体   English

Websocket无限循环循环。 它真的比ajax好吗?

[英]Websocket with endless loop cycling. its really better than ajax?

I am trying understand websockets. 我正在尝试理解websockets。

I have seen 2 examples here in doc and also here . 在doc这里看过2个例子。

Both examples are using endless loop cycling, listening for when a new client connects, when they do something interesting and when they are disconnected. 这两个示例都使用无限循环循环,在新客户端连接时进行侦听,在执行有趣操作时以及何时断开连接时进行侦听。

My question is: Is using websockets (with endless loop cycling) better than an ajax solution with http requests per x time ? 我的问题是:使用websockets(无限循环循环)比使用每x时间http请求的ajax解决方案更好吗?

AJAX and WebSockets are vastly different. AJAX和WebSockets有很大的不同。 Asking if one is better than the other is like asking if a screwdriver is better than a hammer. 询问一个人是否比另一个好,就像问一把螺丝刀是否比锤子更好。

WebSockets are used for real time, interactive communication. WebSockets用于实时交互式通信。 Both sides of a WebSocket connection can send data and it will be received within milliseconds by the other end. WebSocket连接的两端都可以发送数据,另一端会在几毫秒内收到数据。 The connection stays open, reducing latency due to connection negotiation. 连接保持打开状态,减少了连接协商引起的延迟。

However, it only sort of plays nicely with HTTP. 但是,它只能与HTTP很好地配合使用。 That is, it plays nicely with proxies that are WebSocket aware, and with firewalls. 也就是说,它可以很好地与WebSocket识别的代理和防火墙一起使用。 WebSocket traffic is most definitely not HTTP traffic, except for the client's first packet, which requests switching from HTTP to the WebSocket protocol. WebSocket流量绝对不是HTTP流量,除了客户端的第一个数据包,它请求从HTTP切换到WebSocket协议。

AJAX, on the other hand, is pure HTTP. 另一方面,AJAX是纯HTTP。 The only difference between AJAX and a standard web request is that an AJAX request is initiated by client side scripts and the response is available to that same script rather than reloading the page. AJAX和标准Web请求之间的唯一区别是AJAX请求由客户端脚本启动, 并且响应可用于同一脚本而不是重新加载页面。

In both AJAX and WebSockets, the client scripts can receive data and use it within that same script. 在AJAX和WebSockets中,客户端脚本可以接收数据并在同一脚本中使用它。 That's where the similarities end. 这就是相似之处的结束。

WebSockets set up a permanent connection and both sides can send data at any time, or sit quietly at any time. WebSockets建立了永久连接,双方可以随时发送数据,也可以随时静静地坐着。 With AJAX, the client makes a request and the server responds. 使用AJAX,客户端发出请求,服务器响应。

For instance, if you were to set up a new message notification system, if you were using WebSockets, then as soon as a new message is available, the server sends it straight to the browser. 例如,如果您要设置新的消息通知系统,如果您使用的是WebSockets,则只要有新消息可用,服务器就会将其直接发送到浏览器。 If there are no new messages, the server stays quiet. 如果没有新消息,则服务器保持安静。 If you were using AJAX, the client would periodically send a request to the server, which would always respond, either saying there were no new messages, or delivering the notifications that are pending. 如果您使用的是AJAX,客户端会定期向服务器发送请求,该服务器始终会响应,要么说没有新消息,要么发送待处理的通知。 There is no way for the server to initiate things on its end, it must wait for the AJAX request. 服务器无法在其结束时启动,它必须等待AJAX​​请求。

Server side, things diverge from the traditional PHP web development paradigms. 服务器端,事情与传统的PHP Web开发范例不同。 A typical WebSocket server will be a stand alone, CLI application running as a daemon. 典型的WebSocket服务器将是一个独立的CLI应用程序,作为守护进程运行。 (If that last sentence doesn't make sense, please spend a while taking the time to really understanding how to administer a server.) (如果最后一句话没有意义,请花些时间花时间真正了解如何管理服务器。)

This means that multiple clients will be connecting to the same script, and superglobal variables like $_GET and $_SESSION will be absolutely meaningless. 这意味着多个客户端将连接到同一个脚本,而像$_GET$_SESSION这样的超全局变量将毫无意义。 It seems easy to conceptualize in a small use case, but remember that you will most likely want to get information from other parts of your site, which often means using libraries and frameworks that have absolutely no concept of accessing data outside of the HTTP request/response model. 在一个小用例中概念化似乎很容易,但请记住,您很可能希望从站点的其他部分获取信息,这通常意味着使用绝对没有访问HTTP请求之外的数据的概念的库和框架/响应模型。

Thus, for simplicity, you'll usually want to stick with AJAX requests and periodic polling, unless you have the means to rethink the network data and possibly re-implement things that your libraries automate, if you're looking to update standard web traffic. 因此,为简单起见,您通常希望坚持使用AJAX请求和定期轮询,除非您有办法重新考虑网络数据并可能重新实现库自动化的功能,如果您希望更新标准Web流量。

As for the server's loop: 至于服务器的循环:

It is not a busy loop, it is an IO blocked loop. 它不是一个繁忙的循环,它是一个IO阻塞循环。

If the server tries to read network data and none is available, the operating system will block (pause) the script and go off to do whatever else needs to be done. 如果服务器尝试读取网络数据并且没有可用,则操作系统将阻止(暂停)脚本并继续执行其他任何需要完成的操作。 In my WS server, I block waiting for network traffic for at most 1 second at a time, before the script returns to check and see if anything else new happened that I should notify my clients of. 在我的WS服务器中,我阻止等待网络流量一次最多1秒,然后脚本返回检查并查看是否还有其他新事件发生,我应该通知我的客户。 Typically, this is barely a few milliseconds before the server goes right back to its IO blocked state waiting for new data on the wire. 通常,在服务器返回其IO阻塞状态等待线路上的新数据之前,这几乎是几毫秒。 Some others have implemented my server using LibEv, which allows them to respond to events outside of the network IO without having to wait for the block to timeout. 其他一些使用LibEv实现了我的服务器,它允许它们响应网络IO之外的事件,而不必等待块超时。

This is the way nearly every server does things. 这几乎是每个服务器都能做到的事情。 This is why you can have Apache actively listening and serving web traffic without every server that runs Apache being pegged at 100% CPU usage even when there is no traffic. 这就是为什么你可以让Apache主动监听和服务网络流量,而不管每台运行Apache的服务器是否以100%的CPU使用率挂钩,即使没有流量也是如此。

In closing, WebSockets is a wonderful technology, but web libraries and frameworks are simply not built to use them. 最后,WebSockets是一项很棒的技术,但是Web库和框架并不是为了使用它们而构建的。 Thus, unless you're working in a system where waiting 3 seconds for a full AJAX request is far, far too long, it's probably best to use AJAX. 因此,除非你在一个完整的AJAX请求等待3秒的系统中工作太长,否则最好使用AJAX。 If you're writing a multiplayer interactive game or a chat system, then you've found a perfect use for WebSockets. 如果您正在编写多人互动游戏或聊天系统,那么您已经找到了WebSockets的完美用法。

I do heartily encourage everyone to learn WebSockets... but it's not a magic bullet, and few parts of the web are designed in ways where people can get real use out of it. 我衷心鼓励大家学习WebSockets ...但它并不是一个神奇的子弹,网络的很少部分都是以人们可以真正使用它的方式设计的。

Yes, sockets are better in many cases. 是的,在许多情况下,插座更好。

It's not forever loop with 100% cpu utilizing , it's just liveloop, which exists in each daemon application. 它不是forever loop with 100% cpu utilizing ,它只是liveloop,它存在于每个守护进程应用程序中。

Sync accept operation is where 99.99% of time we are. 同步accept操作是我们99.99%的时间。

Ajax heartbeat is more traffic, more server CPU and memory. Ajax心跳是更多的流量,更多的服务器CPU和内存。

I too am in the learning phase. 我也处于学习阶段。 I have built a php-based websocket server and have it communicating with web pages. 我已经构建了一个基于php的websocket服务器,并与网页进行通信。 Perhaps my 2c perspective is useful. 也许我的2c视角很有用。

Getting the websocket server (wss) working using available sources as a starting point is not that difficult, but what to do with it all next is. 让websocket服务器(wss)使用可用的源作为起点并不困难,但接下来要做的就是如何处理它。

The wss runs in CLI version of php. wss在CLI的CLI版本中运行。 Late model browser loads a normal http or https page containing a request to the wss, along with anything else that page needs to do, a handshake occurs. 后期模型浏览器加载包含对wss的请求的普通http或https页面,以及页面需要执行的任何其他操作,发生握手。 Communication is then possible directly between browser and wss at the whim of either end. 然后可以在浏览器和wss之间直接进行通信。 This is low overhead and hence fast and simple. 这是低开销,因此快速而简单。 Very cool. 很酷。 What is said over that link needs to be understood by both ends - subprotocol agreement. 关于该链接的内容需要被两端理解 - 子协议。 You may have to roll your own in php and in javascript. 你可能不得不在php和javascript中自己推出。 No more http headers, urls, etc etc. 没有更多的http标题,网址等。

The wss is a long-lived, stateful instance of php (very unlike apache etc which forget you on sending the page). wss是一个长寿的,有状态的php实例(非常不像apache等,忘了你发送页面)。 An entire app can be run in the wss instance, keeping state for itself and each connected client. 整个应用程序可以在wss实例中运行,为自己和每个连接的客户端保持状态。 It used to be said that php was too leaky for long life but I don't hear that much any more. 曾经有人说,php太长时间没有泄漏,但我不再听到那么多了。 But I believe you still have to be careful with memory. 但我相信你还是要小心记忆。

However, being a single php instance there is not the usual separation between client instances. 但是,作为单个php实例,客户端实例之间通常没有分离。 For example statics in classes are shared with every class instance and hence every client. 例如,类中的静态与每个类实例共享,因此与每个客户端共享。 So for a single user style app sharing data with a heap of clients this is great. 因此,对于与一堆客户端共享数据的单个用户样式应用程序,这非常棒。 I can see that Ajax type calls can be replaced in this way, but if the app still had to rebuild state to service each client, and then release it to save resources, that seems to lessen the advantage. 我可以看到Ajax类型的调用可以用这种方式替换,但是如果应用程序仍然必须重建状态来为每个客户端提供服务,然后释放它以节省资源,那么这似乎会减少优势。

Going a step further and keeping truly stateful instances for clients seems like a possible next step. 更进一步,为客户保持真正有状态的实例似乎可能是下一步。 Replicating the traditional session based system is one possibility, alternatively fork new php interpreters and look after communications between parent and children via sockets or suchlike. 复制传统的基于会话的系统是一种可能性,或者分叉新的PHP解释器并通过套接字等来管理父母和孩子之间的通信。 But this would require resources per client that would be severely limiting for any non-trivial app. 但这需要每个客户端的资源,这将严重限制任何非平凡的应用程序。

Or perhaps it is possible to put the bulk of the app in the parent and let the children just do the very client specific stuff. 或者也许可以将大部分应用程序放在父级中,让孩子们只做客户特定的事情。 Or break the app design into small independent units that can communicate directly via sockets. 或者将应用程序设计分解为可以通过套接字直接通信的小型独立单元。 Socket communication does seem to be catching on nowadays. 现在,套接字通信似乎正在流行起来。

As Ghedpunk says in so many ways, the real world does not yet seem ready to realise the full potential of the web socket concept but it can certainly replace Ajax. 正如Ghedpunk在很多方面所说,现实世界似乎还没有准备好实现Web套接字概念的全部潜力,但它肯定可以取代Ajax。 The added advantage of the server sending without being asked opens up new possibilities previously too difficult to consider. 服务器发送而不被问到的附加优势开辟了以前难以考虑的新可能性。

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

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