如何在php套接字中连续运行server.php

Posted

技术标签:

【中文标题】如何在php套接字中连续运行server.php【英文标题】:How to continuously run the server.php in php socket 【发布时间】:2019-09-02 20:49:31 【问题描述】:

整体代码有效,但问题是我需要每次刷新server.php 才能运行整个代码。如何让服务器连续运行而无需刷新server.php

Client.php

<?php
$host    = "localhost";
$port    = 1024;
$message = "Hello 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 "<br>"."Reply From Server  :".$result;
// close socket
socket_close($socket) ?>

Server.php

<?php
// set some variables
$host = "localhost";
$port = 1024;
// 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";
socket_write($spawn, $output, strlen ($output)) or die("Could not write  output\n");
// close sockets
socket_close($spawn);
socket_close($socket);
?>

【问题讨论】:

这里使用的是哪个操作系统? @dbf 我用的是windows 【参考方案1】:

元刷新。我知道你可以设置间隔。即使在一秒或毫秒也可能导致延迟,对于第二个选项,流式传输可能也是如此。.dotnet 具有编写良好的流式传输类。

【讨论】:

以上是关于如何在php套接字中连续运行server.php的主要内容,如果未能解决你的问题,请参考以下文章

用 PHP 编写套接字服务器是个好主意吗?

如何在后台连续运行 ajax 请求?

如何在 linux 主机中运行 php 套接字服务器

如何在 PHP 中使用基本 HTTP 身份验证?

[PHP]$_SERVER参数详情

PHP_$_SERVER_说明详解