如何使用php socket编程连接到不同的IP地址

时间:2013-11-05 05:12:40

标签: php apache sockets wampserver

我已经在一个系统中安装了wampserver,其IP地址为172.16.127.105并运行 serverphp程序为

{
// set some variables
$host = "172.16.127.105";
$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);
}

我已经在其他系统中使用ip地址172.16.127.106安装了wampserver并运行我的client.php程序

{ 
    $host    = "171.16.127.105";
    $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);

}

当我在不同系统中运行这两个程序时,我在客户端计算机(172.16.127.106)中收到错误,因为请求的计算机(服务器 - 172.16.127.105)不断拒绝请求。

任何人都可以说出真正的问题吗?

我想更改任何apache配置吗?

提前致谢。

0 个答案:

没有答案