我创建了一个简单的bash文件来运行php文件,如下所示:
ws.sh
!#/bin/bash
php -q /var/www/htdocs/server.php
server.php
<?php
// prevent the server from timing out
set_time_limit(0);
session_start();
// include the web sockets server script (the server is started at the far bottom of this file)
require 'class.PHPWebSocket.php';
// when a client sends data to the server
function wsOnMessage($clientID, $message, $messageLength, $binary) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );
// check if message length is 0
if ($messageLength == 0) {
$Server->wsClose($clientID);
return;
}
$_SESSION['currentId'] = $message;
}
// when a client connects
function wsOnOpen($clientID){
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );
$Server->log( "$ip ($clientID) has connected. ");
$data = array('connectionId' => $clientID,'msg'=>'Connected');
$Server->wsSend($clientID, json_encode($data));
}
// when a client closes or lost connection
function wsOnClose($clientID, $status) {
global $Server;
$ip = long2ip( $Server->wsClients[$clientID][6] );
$Server->log( "$ip ($clientID) has disconnected. sess = ".$session_id );
}
// start the server
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
$Server->wsStartServer('server-ip-here', 81);
?>
然后在我的终端上,我将运行bash文件到后台
./ws.sh &
现在,问题是如果bash文件在后台运行,客户端无法连接到我的websocket,并返回一个错误"CONNECTION REFUSED"但如果是正常运行(不是后台),我必须连接到它的问题。任何想法?请帮助。谢谢你!
已经明白了。我把php命令行改成:
php -q /var/www/htdocs/server.php >/dev/null 2>&1 &