且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当用户关闭页面时,如何停止运行服务器发送的事件脚本?的PHP

更新时间:2023-12-01 20:15:04

连接套接字关闭后,PHP脚本应该被杀死。如果脚本在用户关闭页面后仍继续运行,则说明Apache / PHP配置存在严重问题。

The PHP script should be killed as soon as the connection socket closes. If the script keeps on running when the user closes the page, there is something very wrong with your Apache/PHP configuration.

当客户端调用 EventSource.close()显然是由于网络问题导致连接丢失,客户端关闭页面或您的PHP脚本终止。

Socket closing can happen when the client calls EventSource.close() explicitely, the connection is lost due to network problems, the client closes the page or your PHP script terminates.

ignore_user_abort(false)不执行任何操作;这是默认行为(关闭连接后脚本会终止)。传递 true 作为参数会使您的脚本在连接中幸存下来,但这不能解决您的问题。

ignore_user_abort(false) does nothing; that's the default behaviour (the script terminates when the connection is closed). Passing true as a parameter would have your script survive the connection, but that would not solve your problem.

您的 retry:1000 没有用,因为您永远不会关闭套接字服务器端。
当客户端激活 EventSource 对象并仅在客户端请求时终止(或者如果网络失败),则应调用PHP脚本,因此无论初始DB怎样调整每个聊天连接只能出现一次。假设客户端没有做任何会关闭连接的操作。

Your retry: 1000 serves no purpose since you're never closing the socket server-side. Your PHP script should be called when the client activates an EventSource object and terminate only at the client's request (or if the network fails), so whatever initial DB tweaking should occur only once per chat connection. That's assuming the client does not do anything that would close the connection.

顺便说一句,这会对服务器造成很大的压力:每个聊天的客户端都有一个PHP进程在整个聊天过程中一直运行,并且轮询时间间隔太小大约10倍(10秒就足够了)。让客户每30秒左右轮询一次新消息,这样就不会浪费很多钱。

Btw this will put a lot of strain to the server: you will have one PHP process per chatting client running for the whole chat duration, and the polling period is about 10 times too small (10 seconds is more than enough). Having the clients poll for new messages every 30 seconds or so would be less wasteful.