保持套接字服务器在CentOS上运行,以监听php中的客户端请求



我有一个客户端和服务器程序,我不知道如何在我的CENTOS服务器上自动启动服务器,服务器应该继续运行,不管我的浏览器是关闭的,它一直在听客户端请求。请帮助

Server.php

<?php
// set some variables
$host = "XX.XX.XXX.XX";
$port = 25763;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socketn");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socketn");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listenern");
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connectionn");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read inputn");
// clean up input string
$input = trim($input);
echo "Client Message : ".$input;
// reverse client input and send back
$output = strrev($input) . "n";
echo $spawn;
socket_write($spawn, $output, strlen ($output)) or die("Could not write outputn");
// close sockets
socket_close($spawn);
socket_close($socket);
?>

Client.php

<?php
// where is the socket server?
$host    = "XX.XX.XXX.XX";
$port    = 25763;
$message = "Hello Server This is the first message to the server";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socketn");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to servern");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to servern");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server responsen");
echo "Reply From Server  :".$result;
// close socket
socket_close($socket);
    // print result to browser
?>

一般来说,您应该以exec()开始。php文件,例如:

exec('/usr/bin/php /var/www/directory/server/event_server.php');

接下来,把你的socket_accept()(虽然,我使用不同的方案,与socket_select())在无限循环中,不要忘记延迟-这是非常重要的,因为你不想挂起你的CPU:

$broadcast_start = microtime(true);
while(TRUE) {
    socket_accept($socket);
    //Do stuff...
    if( round(microtime(true) - $broadcast_start, 1) < 0.5 ) {
        usleep(500000);
    }
}

但实际上,你的主题真的很复杂。你应该首先在网上搜索解决方案,那里有很多。

相关内容

  • 没有找到相关文章

最新更新