PHP Socket编程 : Server not accessible from outside network

标签 php sockets networking portforwarding

我正在从事 PHP 套接字编程项目。在这个项目中,我们将在 php socket 中创建一个服务。该套接字将监听一个特定端口。来自外部网络的客户端将能够在该端口上进行通信。

到目前为止,我已经能够在 php 中为套接字编程创建服务器和客户端。现在我的电脑已连接到局域网,所以我必须使用端口转发将我的电脑与外部客户端连接起来。我转发端口 2000,该端口上的所有通信都转移到我的电脑 IP 地址。我有 netgear 路由器 n150 无线 adsl。我在该路由器上添加了所有配置。我在此站点在线测试端口转发http://www.yougetsignal.com/tools/open-ports/它说端口已打开。

我在本地(内联网)测试我的代码,它工作正常。但是当我试图在我的电脑和客户端上运行服务器时,我的 ipage 托管服务器是 Web 服务器。它抛出错误“服务器无法连接到服务器”。

服务器.php

<?php

// set some variables
// My LAN Ip
$host = "192.168.0.5";
$port = 2000;
// 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");  
$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);
?>

客户端.php

        <?php
         //my public ip
        $host = "117.223.90.191";
        // port on which I port forword
        $port = 2000;
        $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);
        ?>

任何问题的建议。我想很多人都会遇到和我一样的问题。

最佳答案

即使我认为问题出在 lan 转发中,请尝试使用以下方法对其进行测试:

telnet 117.223.90.191 2000

另一件事是让服务器监听所有接口(interface)

$host = "0.0.0.0";

看看http://reactphp.org/

关于PHP Socket编程 : Server not accessible from outside network,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29861947/

相关文章:

c - src dest ip + port 的哈希函数

php - 如何检查 CodeIgniter 中单个 where 子句的多个条件?

PHP 比较 2 个整数并用更大的整数更新表

php - 使用 wp_mail() 发送 HTML 电子邮件时,CSS 将不起作用

不带引号的 PHP 字符串比较

c TCP 原始套接字选项

sockets - 通过 SSL/HTTPS REST Api 发布 Android 正在响应 400 错误请求

linux - Docker守护程序套接字配置

c++ - Linux上的C/C++多线程服务器/客户端崩溃

java - 如何在 java 中通过 tcp/ip 网络连接发送用户定义的类对象?