Class pour sockets

Contenu du snippet

Voici une class pour les sockets permettant la simplification et la compréhension de comment se déroule cette phase.

Rien de particulier à citer mise à part que tout est dans la source.

Source / Exemple :


<?php
 /*
 --------------------------------------------
 ---Création: 13 Janvier 2008
 ---Modification: 16 Février 2008
 ---Auteur: Romain 'xSTyled' L.
  --------------------------------------------
 #vars
#public
Tableau des erreurs
 #array errors

#private
Tableau des nouveaux clients
 #array newclients
 
Tableau des connexions
 #array sockets
 
 #fonctions
#public
Ecoute un port [Retourne true si ça a réussi, false sinon]
 #bool listen ((string) nom, (string) ip, (int) port)

Se connecte à une machine distante [Retourne true si ça a réussi, false sinon]
 #bool connect ((string) nom, (string) ip, (int) port [, (string) localip ])

Lit une socket [Retourne la ligne reçue, false si la connexion n'existe pas]
 #mixed read ((string) nom [, (int) longueur ])

Retourne le nom du nouveau client s'il y en a un [false s'il n'y en a pas ou si la connexion n'existe pas]
 #mixed newclient ((string) nom)

Ferme une socket [Retourne true si ça a réussi, false sinon]
 #bool close ((string) nom)

Ecrit sur une socket [Retourne true si ça a réussi, false sinon]
 #bool write ((string) nom, (string) data, [, (bool) crlf ])

Renomme une connexion [Retourne true si ça a réussi, false sinon]
 #bool rename ((string) nom, (string) nouveau nom)

Verifie si une connexion existe [Retourne true si la connexion existe, false sinon]
 #bool exists ((string) nom)

Retourne les infos sur une connexion [Retourne false si la connexion n'existe pas]
 #mixed infos ((string) nom)

#private
Retourne le type d'une connexion [false si la connexion n'existe pas ou s'il y a une erreur]
 #mixed gettype ((string) nom)

Retourne le nom d'une connexion avec sa ressource socket. [false si la connexion n'existe pas]
 #mixed getnamebysocket ((ressource) socket)

  • /
class socket { private $sockets = Array(); private $newclient = Array(); public $errors = Array(); public function listen($name, $ip, $port) { $name = strtolower($name); if ($this->exists($name)) { $this->errors[] = 'socket name '.$name.' already exists (line: '.__LINE__.')'; return false; } if (!($a = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { $this->errors[] = socket_strerror(socket_last_error()).' (line: '.__LINE__.')'; return false; } if (!@socket_set_option($a, SOL_SOCKET, SO_REUSEADDR, 1)) { $this->errors[] = socket_strerror(socket_last_error($a)).' (line: '.__LINE__.')'; return false; } if (!@socket_bind($a, $ip, $port)) { $this->errors[] = socket_strerror(socket_last_error($a)).' (line: '.__LINE__.')'; return false; } if (!@socket_listen($a)) { $this->errors[] = socket_strerror(socket_last_error($a)).' (line: '.__LINE__.')'; return false; } if (!@socket_set_nonblock($a)) { $this->errors[] = socket_strerror(socket_last_error($a)).' (line: '.__LINE__.')'; return false; } $this->sockets[$name]['sock'] = $a; $this->sockets[$name]['read'] = ''; $this->sockets[$name]['ip'] = $ip; $this->sockets[$name]['port'] = $port; $this->sockets[$name]['type'] = 'server'; return true; } public function connect($name, $ip, $port, $localip = '0.0.0.0') { $name = strtolower($name); if ($this->exists($name)) { $this->errors[] = 'socket name '.$name.' already exists (line: '.__LINE__.')'; return false; } if (!($r = @gethostbyname($localip))) { $this->errors[] = 'Unable to resolve '.$localip.' (line: '.__LINE__.')'; return false; } else $localip = $r; if (!($a = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { $this->errors[] = socket_strerror(socket_last_error()).' (line: '.__LINE__.')'; return false; } if (!@socket_bind($a, $localip)) { $this->errors[] = socket_strerror(socket_last_error($a)).' (line: '.__LINE__.')'; return false; } if (!@socket_connect($a, $ip, $port)) { $this->errors[] = socket_strerror(socket_last_error($a)).' (line: '.__LINE__.')'; return false; } if (!@socket_set_nonblock($a)) { $this->errors[] = socket_strerror(socket_last_error($a)).' (line: '.__LINE__.')'; return false; } $this->sockets[$name]['sock'] = $a; $this->sockets[$name]['read'] = ''; $this->sockets[$name]['ip'] = $ip; $this->sockets[$name]['port'] = $port; $this->sockets[$name]['type'] = 'client'; return true; } public function read($name, $length = 1024) { $name = strtolower($name); if (!$this->exists($name)) { $this->errors[] = 'Unknow socket name '.$name.' (line: '.__LINE__.')'; return false; } $a = Array(); foreach ($this->sockets as $b => $c) { if (isset($c['sock'])) $a[] = $c['sock']; else unset($this->sockets[$b]); } if (((bool) $a) && (socket_select($a, $write = NULL, $except = NULL, 0) !== false)) { foreach ($a as $b) { if ($this->gettype($this->getnamebysocket($b)) == 'server') { $i = null; $j = null; if ($z = @socket_accept($b)) { $x = (function_exists('mt_rand') ? 'mt_rand' : 'rand'); for ($y = chr($x(97,122)).chr($x(97,122)).chr($x(97,122)).chr($x(97,122)); $this->exists($y); ); socket_getpeername($z, $i, $j); $this->sockets[$y]['server'] = $this->getnamebysocket($b); $this->sockets[$y]['sock'] = $z; $this->sockets[$y]['read'] = ''; $this->sockets[$y]['ip'] = $i; $this->sockets[$y]['port'] = $j; $this->sockets[$y]['type'] = 'serverclient'; $this->newclient[$y] = $this->getnamebysocket($b); } } else { $c = @socket_read($b, $length, PHP_BINARY_READ); if ((!strlen($c)) || ($c === false)) { if ($this->sockets[$name]['read'] === false) { if (($d = $this->getnamebysocket($b)) !== false) $this->close($d); else @socket_close($b); return false; } $c = $this->sockets[$name]['read']; $this->sockets[$name]['read'] = false; return $c; } else { if ((($d = $this->getnamebysocket($b)) !== false)) { $this->sockets[$d]['read'] .= $c; } } } } } if ($a =& $this->sockets[$name]['read']) { if (preg_match("/^([^\n]*)[\n](.*)/s", $a, $r)) { $a = $r[2]; return str_replace(Array("\r", "\n"), '', $r[1]); } } return ''; } public function newclient($name) { $name = strtolower($name); if (!$this->exists($name)) { $this->errors[] = 'Unknow socket name '.$name.' (line: '.__LINE__.')'; return false; } if ($this->gettype($name) != 'server') { $this->errors[] = 'listenqueue: '.$name.' is not a server socket (line: '.__LINE__.')'; return false; } if ((bool) $this->newclient) { foreach ($this->newclient as $a => $b) { if ($b == $name) { unset($this->newclient[$a]); return $a; } } } return false; } public function close($name) { $name = strtolower($name); if (!$this->exists($name)) { $this->errors[] = 'Unknow socket name '.$name.' (line: '.__LINE__.')'; return false; } if (isset($this->newclient[$name])) unset($this->newclient[$name]); if (isset($this->sockets[$name]['sock'])) @socket_close($this->sockets[$name]['sock']); unset($this->sockets[$name]); return true; } public function write($name, $data, $lf = true) { $name = strtolower($name); if (!$this->exists($name)) { $this->errors[] = 'Unknow socket name '.$name.' data : '.(ereg('PASS',$data) === 1 ? 'PASS ******' : $data).' (line: '.__LINE__.')'; return false; } if ($lf) $data .= "\n"; if ((socket_write($this->sockets[$name]['sock'], $data, strlen($data))) === false) return false; return true; } public function rename($name, $newname) { $name = strtolower($name); $newname = strtolower($newname); if (!$this->exists($name)) { $this->errors[] = 'Unknow socket name '.$name.' (line: '.__LINE__.')'; return false; } if ($this->exists($newname)) { $this->errors[] = 'Socket name '.$newname.' already exists (line: '.__LINE__.')'; return false; } $this->sockets[$newname] = $this->sockets[$name]; unset($this->sockets[$name]); return true; } public function exists($name) { $name = strtolower($name); if (isset($this->sockets[$name])) return true; return false; } private function getnamebysocket($sock) { foreach ($this->sockets as $a => $b) { if ($b['sock'] == $sock) return $a; } return false; } private function gettype($name) { $name = strtolower($name); if (!$this->exists($name)) { $this->errors[] = 'Unknow socket name '.$name.' (line: '.__LINE__.')'; return false; } if (isset($this->sockets[$name]['type'])) return $this->sockets[$name]['type']; $this->errors[] = 'Unknow option \'type\' for socket '.$name.' (line: '.__LINE__.')'; return false; } public function infos($name) { $name = strtolower($name); if (!$this->exists($name)) { $this->errors[] = 'Unknow socket name '.$name.' (line: '.__LINE__.')'; return false; } $a = Array('ip' => NULL, 'port' => NULL, 'type' => NULL); $b = $this->sockets[$name]; if (isset($b['ip'])) $a['ip'] = $b['ip']; if (isset($b['port'])) $a['port'] = $b['port']; if (isset($b['type'])) $a['type'] = $b['type']; if (isset($b['server'])) $a['server'] = $b['server']; return $a; } public final function __construct() { if (!extension_loaded('sockets')) { if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') { @dl('php_sockets.dll') or die('You must have installed socket extension.'); } else { @dl('sockets.so') or die('You must have installed socket extension.'); } } } } ?>

Conclusion :


N'hésitez pas pour les commentaires intéressant et évolutif. Merci
Merci a winwarrior pour la base même de la source

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.