PHP socket_listen() 不工作
PHP socket_listen() not working
我正尝试在 PHP 中学习 Socket 编程。我得到了一个教程。我遵循了教程中的精确代码,但我的代码 returns
无法侦听套接字 [22]:参数无效错误。
我认为这更多是服务器错误,而不是代码本身的错误。我是 运行 XAMPP 服务器 Ubuntu。
#!/opt/lampp/bin/php
<?php
// set some variables
$host = "127.0.0.1";
$port = 80;
// don’t timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die('Could not create socketn');
// bind socket to port socket_connect($socket, '/var/run/mysqld/mysqld.sock')
$result = socket_connect($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 = "red";//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');
echo ($output);
// close sockets
socket_close($spawn);
socket_close($socket);
?>
由于您正在尝试监听一个端口,而不是进行传出连接,因此您的 socket_connect
应该改为 socket_bind
(您的评论已经暗示)
$result = socket_bind($socket, $host, $port) or die('Could not bind to socketn')
此外,您应该知道监听低于 1024 的端口需要您以 root 运行 脚本(不推荐用于实验),因此您可能需要更改为高于 1024 的端口以能够 运行 作为普通用户。
我正尝试在 PHP 中学习 Socket 编程。我得到了一个教程。我遵循了教程中的精确代码,但我的代码 returns
无法侦听套接字 [22]:参数无效错误。
我认为这更多是服务器错误,而不是代码本身的错误。我是 运行 XAMPP 服务器 Ubuntu。
#!/opt/lampp/bin/php
<?php
// set some variables
$host = "127.0.0.1";
$port = 80;
// don’t timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die('Could not create socketn');
// bind socket to port socket_connect($socket, '/var/run/mysqld/mysqld.sock')
$result = socket_connect($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 = "red";//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');
echo ($output);
// close sockets
socket_close($spawn);
socket_close($socket);
?>
由于您正在尝试监听一个端口,而不是进行传出连接,因此您的 socket_connect
应该改为 socket_bind
(您的评论已经暗示)
$result = socket_bind($socket, $host, $port) or die('Could not bind to socketn')
此外,您应该知道监听低于 1024 的端口需要您以 root 运行 脚本(不推荐用于实验),因此您可能需要更改为高于 1024 的端口以能够 运行 作为普通用户。