我无法在php中运行客户端/服务器程序

时间:2012-09-29 00:43:21

标签: php sockets client-server

这是我试图运行的程序:

$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选项但仍然遇到无法绑定的错误。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

适合我。

可能出现的问题:

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

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

<强> TEST

$ 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.