0

我在服务器上有一个交互式 cli 程序(游戏)。我想创建一个与该程序通信的网络应用程序。proc_open 似乎可以解决问题,但我必须在处理每个请求后关闭该进程。

此过程输出需要发送到客户端,客户端将使用适当的输入进行响应。因为这是一个游戏,所以这个循环可以持续一段时间。

我的问题是:如何在等待客户端输入时保持服务器上的进程运行。

我做了一些研究,我想知道 Ratchet IO (websockets) 是否是最好的方法?

4

1 回答 1

0

假设您有一个 php 标签,我建议您创建一个 php 脚本,该脚本可以使用运行棘轮 wsserver 的命令行运行。

我可以给你一个为 laravel 命令行编写的例子:

class StartServer extends Command {

/**
 * The console command name.
 *
 * @var string
 */
protected $name = 'start:server';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Start WebSocket server';

/**
 * Create a new command instance.
 *
 * @return void
 */
public function __construct()
{
    parent::__construct();
}

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function fire()
{
    // This variable can be utilized before running the server
    $socket_server = new SocketServer();
    $server = IoServer::factory(new HttpServer(new WsServer($socket_server)), PORT);
    $server->run();
}
}

你的 SocketServer 类看起来像这样:

class SocketServer implements MessageComponentInterface
{
    public function __construct()
    {

    }

    public function onOpen(ConnectionInterface $conn) {
        // New connection handle it, store it if necessary, make sure a session and connection is well mapped. Alternatively you can use Ratchet's SessionProvider
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        // Got message, do something with it
    }

    /**
     * @param \Ratchet\ConnectionInterface $conn
     */
    public function onClose(ConnectionInterface $conn) {
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    /**
     * socket Error
     * @param \Ratchet\ConnectionInterface $conn
     * @param \Exception $e
     */
    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
于 2014-11-10T01:38:19.187 回答