【发布时间】:2015-09-30 03:50:31
【问题描述】:
我写了一个小类来管理 PHP 中的套接字连接:
#/usr/bin/php
<?php
define('PORT', 5000);
define('IP', '127.0.0.1');
/**
* SocketManager
*/
class SocketManager {
private $sock = null;
public $errorcode = null;
public $errormsg = null;
public $client = null;
public function initSocket($onConnect) {
echo "Init Socket\n";
if (!($this->sock = socket_create(AF_INET, SOCK_STREAM, 0))) {
$this->errorcode = socket_last_error();
$thid->errormsg = socket_strerror($errorcode);
return;
}
echo "Created Socket\n";
if (!socket_bind($this->sock, IP , PORT)) {
$this->errorcode = socket_last_error();
$thid->errormsg = socket_strerror($errorcode);
return;
}
echo "Bind Socket\n";
if(!socket_listen($this->sock , 10)) {
$this->errorcode = socket_last_error();
$thid->errormsg = socket_strerror($errorcode);
return;
}
echo "Listening on " . PORT . "\n";
while (true) {
echo ".";
$this->client = socket_accept($this->sock);
if(socket_getpeername($client , $address , $port)) {
if (!is_null($onConnect)) {
call_user_func_array($onConnect,array($client,$address,$port));
}
}
}
}
function __construct($onConnect) {
$this->initSocket($onConnect);
}
}
function handleConnection($client,$address,$port) {
echo "User Connected: $address\n";
}
$socket = new SocketManager("handleConnection");
?>
启动它会导致以下输出:
#/usr/bin/php
Init Socket
Created Socket
Bind Socket
Listening on 5000
.
使用 netstat 检查会打印出以下内容:
netstat -nap | grep 听
tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN 32301/php
nmap 还告诉我 5000 端口已打开:
nmap -p 5000 本地主机
PORT STATE SERVICE
5000/tcp open upnp
但是,如果我尝试使用 telnet 连接:
telnet SERVER_IP 5000 我得到:
Trying SERVER_IP...
telnet: connect to address SERVER_IP: Connection refused
telnet: Unable to connect to remote host
我也尝试将 iptables 更改为在端口上接受,但没有成功,但可能是我做错了。
我可以尝试其他任何想法吗?
- xCoder
【问题讨论】:
-
我猜你正在尝试远程登录,而你正在绑定到 127.0.0.1。只需将 IP 更改为 0.0.0.0 就可以连接了。
-
谢谢,这是为我做的!如果您将其作为答案,我可以将其标记为正确。