Bri*_*ian 3 php sockets client
因此,我有此服务器代码,并且可以与我的客户端一起使用。但是它从客户端获取一条消息,然后反向发送一条消息。这是代码:SERVER.php
<?php
$host = "127.0.0.1";
$port = 1234;
// 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);
// 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);
?>
Run Code Online (Sandbox Code Playgroud)
如何编辑此代码,使其可以连续运行?客户端当然不必熬夜,它只会打开一个新的套接字,发送一条消息,从服务器取回它,然后关闭套接字。下次我要发送消息时,将再次执行上一步。
现在,如果我发送一条消息并从服务器获得响应,它们都将关闭套接字。请帮助我修改服务器端,使其不会关闭套接字并等待新的连接。
我试图添加一个while循环,但是客户端关闭后,服务器再次关闭,并说无法再从客户端读取信息。
谢谢
我想到了。你们中的大多数人都像使用while()循环那样快要解决它。但是,您不能只是将代码放入一段时间内并期望它能工作。正确的方法如下:
<?php
$host = "127.0.0.1";
$port = 1234;
// 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");
while(true) {
// 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);
// 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);
?>
Run Code Online (Sandbox Code Playgroud)
如果您尝试将while放置在任何其他地方,则会引入错误。 谢谢大家的帮助:D