在共享主机上用php启动websockets服务器 [英] starting a websockets server in php on shared hosting
问题描述
我有一个使用WebSockets
在PHP
中实现的聊天应用程序( http://code. google.com/p/phpwebsocket/),然后在我的本地主机上进行测试时,我必须通过命令"php server.php"
运行WebSockets服务器,该命令将在本地主机上启动服务器,并且文件一直运行直到我按我的Ubuntu终端上的"Ctrl + c".我的意思是它继续运行while循环,这是非常正常的bcoz,服务器应该可以监听请求.
I have a chat application implemented in PHP
using WebSockets
(http://code.google.com/p/phpwebsocket/), and on my localhost when i test it i have to run the WebSockets server through a command "php server.php"
, which starts the server on localhost and the file keeps running till i press "Ctrl + c" on my Ubuntu terminal. I mean it keeps on running the while loop, which is quite normal bcoz the server should be up to listen to the requests.
现在,我的疑问是我已将此应用程序托管在共享主机上,但该主机没有授予我SSH
访问权限,我的意思是我无法获得以前用于运行命令的界面之类的终端,因此我将如何运行那个server.php
脚本现在启动我的服务器?
Now my doubt is that i have hosted this application on a shared hosting, which does not give me SSH
access, i mean i cannot get a terminal like interface where i used to run my command, so HOW will i run that server.php
script to start my server now?
是的,我提到的一件事我只需要运行一次脚本,然后脚本将继续运行,并且托管提供程序还允许设置cron jobs
.
And yes one thing that i mentioned i just need to run the script once, then the script will keep on running, and also the hosting provider allows to set up cron jobs
.
请帮助,谢谢.
推荐答案
无法通过SSH访问您的共享托管非常困难.那就是...
Not having SSH access to your shared hosting is pretty flaky. That said...
您可以使用 exec
在命令行上从触发脚本.例如,如果您有一个控制器操作,而该操作是从类似 http://mysite.com/server/start的URL调用的,您可以嵌入该行:
You can use exec
to run something on the command line from a triggered script. For instance, if you have a controller action that you call from a URL like http://mysite.com/server/start, you could embed the line:
$lastLine = exec("php server.php");
当然,该命令将在命令完成后才会返回,因此您永远不会从此脚本获得响应(除非失败).因此,我将使用 popen
,它将分叉该过程并立即返回,让您的控制器返回响应.
Of course, this command will not return until the command finishes, so you will never get a response from this script (unless it fails). So I would use popen
, which will fork the process and return right away, allowing your controller to return a response.
$handle = popen("php server.php", "r");
在某个时候,您可能要停止该服务器.您可以使用 passthru
和 http://mysite.com/server/stop 一样,您可以嵌入:
At some point, you are probably going to want to stop this server. You can use passthru
and posix_kill
with a little unix CLI magic to get this done, maybe in another controller action that you call from a URL like http://mysite.com/server/stop, you could embed:
$output = passthru('ps ax | grep server\.php');
$ar = preg_split('/ /', $output);
if (in_array('/usr/bin/php', $ar)) {
$pid = (int) $ar[0];
posix_kill($pid, SIGKILL);
这篇关于在共享主机上用php启动websockets服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!