php监听“;互联网”;


php listen on the "internet"?

使用http://www.codeproject.com/Tips/418814/Socket-Programming-in-PHP

SERVER.PHP:

// set some variables
$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);

CLIENT.PHP:

$host    = "127.0.0.1";
$port    = 25003;
$message = "Hello Server";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket'n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server'n");  
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server'n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response'n");
echo "Reply From Server  :".$result;
// close socket
socket_close($socket);

正如您所看到的,服务器正在侦听127.0.0.1:port,客户端正在连接到127.0.0.1:port

但是,我希望我的客户端和服务器位于两个不同的服务器上。

例如:

我的服务器将在IP 11.22.33.44:1234上侦听,我的客户端将从IP 12.23.45.66:1234 连接

我将使用linux服务器,但现在我正在我的windows机器上这样做。

所以我想听听我的外部IP。当我输入我的外部IP作为主机时,我会抛出错误。

Warning: socket_bind(): unable to bind address [10049]: The requested address is not valid in its context. in C:'xampp'htdocs'server.php on line 12
Warning: socket_listen(): unable to listen on socket [10022]: An invalid argument was supplied. in C:'xampp'htdocs'server.php on line 14
Warning: socket_accept(): unable to accept incoming connection [10022]: An invalid argument was supplied. in C:'xampp'htdocs'server.php on line 17
Warning: socket_read() expects parameter 1 to be resource, boolean given in C:'xampp'htdocs'server.php on line 18
Warning: socket_write() expects paramet

er 1是资源,在第20行上的C:''examplep''htdocs''server.php中给出布尔值

我该怎么做?

谢谢。

由于您(推测!)可能在代理、路由器、防火墙或其他外围设备后面托管此服务,因此您的盒子将无法直接访问绑定到外部IP。因此,将其绑定到localhost,并将外围设备的适用端口转发(打开)到服务器。

例如,如果您使用AWS作为主机,您可以设置防火墙ACL,允许您的套接字端口连接到两台服务器,然后连接应该通过。

这类似于将Apache web服务绑定到服务器的localhost IP地址。

或者,如果您没有托管此网络,并且通信发生在本地网络上,那么您至少应该能够绑定到每个本地网卡的指定/内部IP地址。

打开cmd并编写php-f C:''examplep''htdocs''server.php您的代码