PHP socket_listen()不起作用

时间:2016-03-08 04:37:58

标签: php sockets ubuntu xampp

我正在尝试用PHP学习Socket编程。我抓住了一个教程。我按照教程中的精确代码,但我的代码返回

无法侦听socket [22]:无效的参数错误。

我认为这更多的是服务器错误,而不是代码本身的错误。我在Ubuntu中运行XAMPP Server。

#!/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);


?>

1 个答案:

答案 0 :(得分:0)

由于您正在尝试收听端口,而不是传出连接,因此socket_bind应该是$result = socket_bind($socket, $host, $port) or die('Could not bind to socketn') (您的评论已经建议)

defaultRenderer

此外,您应该知道,收听1024以下的端口需要您以root身份运行脚本(实际上不推荐用于实验),因此您可能希望更改为1024以上的端口以便能够以普通用户。