2

这是我要运行的程序:

$host = "127.0.0.1";
$port = 25003;
// 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);

我在 WAMP 中启用了 PHP_socket 选项,但仍然出现无法绑定等错误。有人可以帮我吗?

4

1 回答 1

0

为我工作。

可能出现的问题:

1) 有另一个程序副本正在运行并锁定端口。

2) 客户端尝试连接到“localhost”而不是“127.0.0.1”。在 Windows 上,我注意到它们不一定相同。根据您的网络安装,“localhost”可能映射到::1IPv6,而127.0.0.1IPv4。

测试

$ php -q test.php &
[1] 2855

# Now we try again a SECOND copy...
$ php -q test.php

PHP Warning:  socket_bind(): unable to bind address [98]: Address already in use in test.php on line 9
Could not bind to socket

$ telnet 127.0.0.1 25003
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
HELLO WORLD.
Client Message : HELLO WORLD..DLROW OLLEH
Connection closed by foreign host.
于 2012-09-29T15:25:48.307 回答