I wrote a small class to manage socket connections in 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");
?>
Starting this will cause the following output:
#/usr/bin/php
Init Socket
Created Socket
Bind Socket
Listening on 5000
.
Checking using netstat prints out the following:
netstat -nap | grep LISTEN
tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN 32301/php
And also nmap tells me the port 5000 is opened:
nmap -p 5000 localhost
PORT STATE SERVICE
5000/tcp open upnp
However still if I try to connect using telnet:
telnet SERVER_IP 5000 I get:
Trying SERVER_IP...
telnet: connect to address SERVER_IP: Connection refused
telnet: Unable to connect to remote host
I also tried altering iptables to accept on the port, but it did not work, but it is possible that I just did it wrong.
Any other idea that I could try out?
You have to change:
define('IP', '127.0.0.1');
with:
define('IP', '0.0.0.0');
By using 127.0.0.1 you will be able to connect only from the server itself, since it binds to 127.0.0.1, just as netstat
shows.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.