0

我有一个客户端和服务器程序,我不知道如何在我的 CENTOS 服务器上自动启动服务器,并且无论我的浏览器是否关闭,服务器都应该继续运行,并且它会继续监听客户端请求。请帮忙

服务器.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 socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");

// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// 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 output\n");
// close sockets
socket_close($spawn);
socket_close($socket);
?>

客户端.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 socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server  :".$result;
// close socket
socket_close($socket);
    // print result to browser
?>
4

1 回答 1

0

通常,您应该以 .php 文件开头exec(),例如:

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

接下来,将您的socket_accept()(虽然,我使用不同的方案,with 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);
    }
}

但实际上,您的主题非常复杂。您应该首先在网上搜索解决方案,这些解决方案很多。

于 2014-07-08T09:35:09.100 回答