| 導購 | 订阅 | 在线投稿
分享
 
 
當前位置: 王朝網路 >> php >> 用PHP的Socket建立自己的聊天室服務器
 

用PHP的Socket建立自己的聊天室服務器

2008-12-19 08:07:43  編輯來源:互聯網  简体版  手機版  評論  字體: ||
 
 
  <?PHP

  /**

  * patServer

  * PHP socket server base class

  * Events that can be handled:

  * * onStart

  * * onConnect

  * * onConnectionRefused

  * * onClose

  * * onShutdown

  * * onReceiveData

  *

  * @version 1.1

  * @author Stephan Schmidt <schst@php-tools.de>

  * @package patServer

  */

  class patServer{

  /**

  * information about the project

  * @var array $systemVars

  */

  var $systemVars = array(

   "appName" => "patServer",

   "appVersion" => "1.1",

   "author" => array("Stephan Schmidt <schst@php-tools.de>", )

   );

  /**

  * port to listen

  * @var integer $port

  */

   var $port = 10000;

  /**

  * domain to bind to

  * @var string $domain

  */

   var $domain = "localhost";

  /**

  * maximum amount of clients

  * @var integer $maxClients

  */

   var $maxClients = -1;

  /**

  * buffer size for socket_read

  * @var integer $readBufferSize

  */

   var $readBufferSize = 128;

  /**

  * end character for socket_read

  * @var integer $readEndCharacter

  */

   var $readEndCharacter = "\n";

  /**

  * maximum of backlog in queue

  * @var integer $maxQueue

  */

   var $maxQueue = 500;

  /**

  * debug mode

  * @var boolean $debug

  */

   var $debug = true;

  /**

  * debug mode

  * @var string $debugMode

  */

   var $debugMode = "text";

  /**

  * debug destination (filename or stdout)

  * @var string $debugDest

  */

   var $debugDest = "stdout";

  /**

  * empty array, used for socket_select

  * @var array $null

  */

   var $null = array();

  /**

  * all file descriptors are stored here

  * @var array $clientFD

  */

   var $clientFD = array();

  /**

  * needed to store client information

  * @var array $clientInfo

  */

   var $clientInfo = array();

  /**

  * needed to store server information

  * @var array $serverInfo

  */

   var $serverInfo = array();

  /**

  * amount of clients

  * @var integer $clients

  */

   var $clients = 0;

  /**

  * create a new socket server

  *

  * @access public

  * @param string $domain domain to bind to

  * @param integer $port port to listen to

  */

  function patServer( $domain = "localhost", $port = 10000 ){

   $this->domain = $domain;

   $this->port = $port;

   $this->serverInfo["domain"] = $domain;

   $this->serverInfo["port"] = $port;

   $this->serverInfo["servername"] = $this->systemVars["appName"];

   $this->serverInfo["serverversion"] = $this->systemVars["appVersion"];

   set_time_limit( 0 );

  }

  /**

  * set maximum amount of simultaneous connections

  *

  * @access public

  * @param int $maxClients

  */

  function setMaxClients( $maxClients ){

   $this->maxClients = $maxClients;

  }

  /**

  * set debug mode

  *

  * @access public

  * @param mixed $debug [text|htmlfalse]

  * @param string $dest destination of debug message (stdout to output or filename if log should be written)

  */

  function setDebugMode( $debug, $dest = "stdout" ){

   if( $debug === false ){

   $this->debug = false;

   return true;

   }

   $this->debug = true;

   $this->debugMode = $debug;

   $this->debugDest = $dest;

  }

  /**

  * start the server

  *

  * @access public

  * @param int $maxClients

  */

  function start(){

   $this->initFD = @socket_create( AF_INET, SOCK_STREAM, 0 );

   if( !$this->initFD )

   die( "patServer: Could not create socket." );

   // adress may be reused

   socket_setopt( $this->initFD, SOL_SOCKET, SO_REUSEADDR, 1 );

   // bind the socket

   if(!@socket_bind( $this->initFD, $this->domain, $this->port ) ){

   @socket_close( $this->initFD );

   die( "patServer: Could not bind socket to ".$this->domain." on port ".$this->port." ( ".$this->getLastSocketError( $this->initFd )." )." );

   }

   // listen on selected port

   if(!@socket_listen( $this->initFD, $this->maxQueue ) )

   die( "patServer: Could not listen ( ".$this->getLastSocketError( $this->initFd )." )." );

   $this->sendDebugMessage( "Listening on port ".$this->port.". Server started at ".date( "H:i:s", time() ) );

   // this allows the shutdown function to check whether the server is already shut down

   $GLOBALS["_patServerStatus"] = "running";

   // this ensures that the server will be sutdown correctly

   register_shutdown_function( array( $this, "shutdown" ) );

   if( method_exists( $this, "onStart" ) )

   $this->onStart();

   $this->serverInfo["started"] = time();

   $this->serverInfo["status"] = "running";

   while( true ){

   $readFDs = array();

   array_push( $readFDs, $this->initFD );

   // fetch all clients that are awaiting connections

   for( $i = 0; $i < count( $this->clientFD ); $i++ )

   if( isset( $this->clientFD[$i] ) )

   array_push( $readFDs, $this->clientFD[$i] );

   // block and wait for data or new connection

   $ready = @socket_select( $readFDs, $this->null, $this->null, NULL );

   if( $ready === false ){

   $this->sendDebugMessage( "socket_select failed." );

   $this->shutdown();

   }

   // check for new connection

   if( in_array( $this->initFD, $readFDs ) ){

   $newClient = $this->acceptConnection( $this->initFD );

   // check for maximum amount of connections

   if( $this->maxClients > 0 ){

   if( $this->clients > $this->maxClients ){

   $this->sendDebugMessage( "Too many connections." );

   if( method_exists( $this, "onConnectionRefused" ) )

   $this->onConnectionRefused( $newClient );

   $this->closeConnection( $newClient );

   }

   }

   if( --$ready <= 0 )

   continue;

   }

   // check all clients for incoming data

   for( $i = 0; $i < count( $this->clientFD ); $i++ ){

   if( !isset( $this->clientFD[$i] ) )

   continue;

   if( in_array( $this->clientFD[$i], $readFDs ) ){

   $data = $this->readFromSocket( $i );

   // empty data => connection was closed

   if( !$data ){

   $this->sendDebugMessage( "Connection closed by peer" );

   $this->closeConnection( $i );

   }else{

   $this->sendDebugMessage( "Received ".trim( $data )." from ".$i );

   if( method_exists( $this, "onReceiveData" ) )

   $this->onReceiveData( $i, $data );

   }

   }

   }

   }

  }

  /**

  * read from a socket

  *

  * @access private

  * @param integer $clientId internal id of the client to read from

  * @return string $data data that was read

  */

  function readFromSocket( $clientId ){

   // start with empty string

   $data = "";

   // read data from socket

   while( $buf = socket_read( $this->clientFD[$clientId], $this->readBufferSize ) ){

   $data .= $buf;

   $endString = substr( $buf, - strlen( $this->readEndCharacter ) );

   if( $endString == $this->readEndCharacter )

   break;

   if( $buf == NULL )

   break;

   }

   if( $buf === false )

   $this->sendDebugMessage( "Could not read from client ".$clientId." ( ".$this->getLastSocketError( $this->clientFD[$clientId] )." )." );

   return $data;

  }

  /**

  * accept a new connection

  *

  * @access public

  * @param resource &$socket socket that received the new connection

  * @return int $clientID internal ID of the client

  */

  function acceptConnection( &$socket ){

   for( $i = 0 ; $i <= count( $this->clientFD ); $i++ ){

   if( !isset( $this->clientFD[$i] ) || $this->clientFD[$i] == NULL ){

   $this->clientFD[$i] = socket_accept( $socket );

   socket_setopt( $this->clientFD[$i], SOL_SOCKET, SO_REUSEADDR, 1 );

   $peer_host = "";

   $peer_port = "";

   socket_getpeername( $this->clientFD[$i], $peer_host, $peer_port );

   $this->clientInfo[$i] = array(

   "host" => $peer_host,

   "port" => $peer_port,

   "connectOn" => time()

   );

   $this->clients++;

   $this->sendDebugMessage( "New connection ( ".$i." ) from ".$peer_host." on port ".$peer_port );

   if( method_exists( $this, "onConnect" ) )

   $this->onConnect( $i );

   return $i;

   }

   }

  }

  /**

  * check, whether a client is still connected

  *

  * @access public

  * @param integer $id client id

  * @return boolean $connected true if client is connected, false otherwise

  */

  function isConnected( $id ){

   if( !isset( $this->clientFD[$id] ) )

   return false;

   return true;

  }

  /**

  * close connection to a client

  *

  * @access public

  * @param int $clientID internal ID of the client

  */

  function closeConnection( $id ){

   if( !isset( $this->clientFD[$id] ) )

   return false;

   if( method_exists( $this, "onClose" ) )

   $this->onClose( $id );

   $this->sendDebugMessage( "Closed connection ( ".$id." ) from ".$this->clientInfo[$id]["host"]." on port ".$this->clientInfo[$id]["port"] );

   @socket_close( $this->clientFD[$id] );

   $this->clientFD[$id] = NULL;

   unset( $this->clientInfo[$id] );

   $this->clients--;

  }

  /**

  * shutdown server

  *

  * @access public

  */

  function shutDown(){

   if( $GLOBALS["_patServerStatus"] != "running" )

   exit;

   $GLOBALS["_patServerStatus"] = "stopped";

   if( method_exists( $this, "onShutdown" ) )

   $this->onShutdown();

   $maxFD = count( $this->clientFD );

   for( $i = 0; $i < $maxFD; $i++ )

   $this->closeConnection( $i );

   @socket_close( $this->initFD );

   $this->sendDebugMessage( "Shutdown server." );

   exit;

  }

  /**

  * get current amount of clients

  *

  * @access public

  * @return int $clients amount of clients

  */

  function getClients(){

   return $this->clients;

  }

  /**

  * send data to a client

  *

  * @access public

  * @param int $clientId ID of the client

  * @param string $data data to send

  * @param boolean $debugData flag to indicate whether data that is written to socket should also be sent as debug message

  */

  function sendData( $clientId, $data, $debugData = true ){

   if( !isset( $this->clientFD[$clientId] ) || $this->clientFD[$clientId] == NULL )

   return false;

   if( $debugData )

   $this->sendDebugMessage( "sending: \"" . $data . "\" to: $clientId" );

   if(!@socket_write( $this->clientFD[$clientId], $data ) )

   $this->sendDebugMessage( "Could not write '".$data."' client ".$clientId." ( ".$this->getLastSocketError( $this->clientFD[$clientId] )." )." );

  }

  /**

  * send data to all clients

  *

  * @access public

  * @param string $data data to send

  * @param array $exclude client ids to exclude

  */

  function broadcastData( $data, $exclude = array(), $debugData = true ){

   if( !empty( $exclude ) && !is_array( $exclude ) )

   $exclude = array( $exclude );

   for( $i = 0; $i < count( $this->clientFD ); $i++ ){

   if( isset( $this->clientFD[$i] ) && $this->clientFD[$i] != NULL && !in_array( $i, $exclude ) ){

   if( $debugData )

   $this->sendDebugMessage( "sending: \"" . $data . "\" to: $i" );

   if(!@socket_write( $this->clientFD[$i], $data ) )

   $this->sendDebugMessage( "Could not write '".$data."' client ".$i." ( ".$this->getLastSocketError( $this->clientFD[$i] )." )." );

   }

   }

  }

  /**

  * get current information about a client

  *

  * @access public

  * @param int $clientId ID of the client

  * @return array $info information about the client

  */

  function getClientInfo( $clientId ){

   if( !isset( $this->clientFD[$clientId] ) || $this->clientFD[$clientId] == NULL )

   return false;

   return $this->clientInfo[$clientId];

  }

  /**

  * send a debug message

  *

  * @access private

  * @param string $msg message to debug

  */

  function sendDebugMessage( $msg ){

   if( !$this->debug )

   return false;

   $msg = date( "Y-m-d H:i:s", time() ) . " " . $msg;

   switch( $this->debugMode ){

   case "text":

   $msg = $msg."\n";

   break;

   case "html":

   $msg = htmlspecialchars( $msg ) . "<br />\n";

   break;

   }

   if( $this->debugDest == "stdout" || empty( $this->debugDest ) ){

   echo $msg;

   flush();

   return true;

   }

   error_log( $msg, 3, $this->debugDest );

   return true;

  }

  /**

  * return string for last socket error

  *

  * @access public

  * @return string $error last error

  */

  function getLastSocketError( &$fd ){

   $lastError = socket_last_error( $fd );

   return "msg: " . socket_strerror( $lastError ) . " / Code: ".$lastError;

  }

  function onReceiveData($ip,$data){

   $this->broadcastData( $data,array(), true );

  }

  }

  $patServer = new patServer();

  $patServer->start();

  ?>
 
 
 
上一篇《php Socket 基礎》
下一篇《PHP用Socket上傳圖片》
 
 
 
 
 
 
日版寵物情人插曲《Winding Road》歌詞

日版寵物情人2017的插曲,很帶節奏感,日語的,女生唱的。 最後聽見是在第8集的時候女主手割傷了,然後男主用嘴幫她吸了一下,插曲就出來了。 歌手:Def...

兄弟共妻,我成了他們夜裏的美食

老鍾家的兩個兒子很特別,就是跟其他的人不太一樣,魔一般的執著。兄弟倆都到了要結婚的年齡了,不管自家老爹怎麽磨破嘴皮子,兄弟倆說不娶就不娶,老父母爲兄弟兩操碎了心...

如何磨出破洞牛仔褲?牛仔褲怎麽剪破洞?

把牛仔褲磨出有線的破洞 1、具體工具就是磨腳石,下面墊一個硬物,然後用磨腳石一直磨一直磨,到把那塊磨薄了,用手撕開就好了。出來的洞啊很自然的。需要貓須的話調幾...

我就是掃描下圖得到了敬業福和愛國福

先來看下敬業福和愛國福 今年春節,支付寶再次推出了“五福紅包”活動,表示要“把欠大家的敬業福都還給大家”。 今天該活動正式啓動,和去年一樣,需要收集“五福”...

冰箱異味産生的原因和臭味去除的方法

有時候我們打開冰箱就會聞到一股異味,冰箱裏的這種異味是因爲一些物質發出的氣味的混合體,聞起來讓人惡心。 産生這些異味的主要原因有以下幾點。 1、很多人有這種習...

《極品家丁》1-31集大結局分集劇情介紹

簡介 《極品家丁》講述了現代白領林晚榮無意回到古代金陵,並追隨蕭二小姐化名“林三”進入蕭府,不料卻陰差陽錯上演了一出低級家丁拼搏上位的“林三升職記”。...

李溪芮《極品家丁》片尾曲《你就是我最愛的寶寶》歌詞

你就是我最愛的寶寶 - 李溪芮 (電視劇《極品家丁》片尾曲) 作詞:常馨內 作曲:常馨內 你的眉 又鬼馬的挑 你的嘴 又壞壞的笑 上一秒吵鬧 下...

烏梅的功效與作用以及烏梅的食用禁忌有哪些?

烏梅,又稱春梅,中醫認爲,烏梅味酸,性溫,無毒,具有安心、除熱、下氣、祛痰、止渴調中、殺蟲的功效,治肢體痛、肺痨病。烏梅泡水喝能治傷寒煩熱、止吐瀉,與幹姜一起制...

什麽是脂肪粒?如何消除臉部脂肪粒?

什麽是脂肪粒 在我們的臉上總會長一個個像脂肪的小顆粒,弄也弄不掉,而且顔色還是白白的。它既不是粉刺也不是其他的任何痘痘,它就是脂肪粒。 脂肪粒雖然也是由油脂...

網絡安全治理:國家安全保障的主要方向是打擊犯罪,而不是處置和懲罰受害者

來源:中國青年報 新的攻擊方法不斷湧現,黑客幾乎永遠占據網絡攻擊的上風,我們不可能通過技術手段杜絕網絡攻擊。國家安全保障的主要方向是打擊犯罪,而不是處置和懲罰...

河南夫妻在溫嶺網絡直播“造人”內容涉黃被刑事拘留

夫妻網絡直播“造人”爆紅   1月9日,溫嶺城北派出所接到南京警方的協查通告,他們近期打掉了一個涉黃直播APP平台。而根據掌握的線索,其中有一對涉案的夫妻主播...

如何防止牆紙老化?牆紙變舊變黃怎麽辦?

如何防止牆紙老化? (1)選擇透氣性好的牆紙 市場上牆紙的材質分無紡布的、木纖維的、PVC的、玻璃纖維基材的、布面的等,相對而言,PVC材質的牆紙最不透氣...

鮮肌之謎非日本生産VS鮮肌之謎假日貨是謠言

觀點一:破日本銷售量的“鮮肌之謎” 非日本生産 近一段時間,淘寶上架了一款名爲“鮮肌之謎的” 鲑魚卵巢美容液,號稱是最近日本的一款推出的全新護膚品,産品本身所...

中國最美古詩詞精選摘抄

系腰裙(北宋詞人 張先) 惜霜蟾照夜雲天,朦胧影、畫勾闌。人情縱似長情月,算一年年。又能得、幾番圓。 欲寄西江題葉字,流不到、五亭前。東池始有荷新綠,尚小如...

關于女人的經典語句

關于女人的經典語句1、【做一個獨立的女人】 思想獨立:有主見、有自己的人生觀、價值觀。有上進心,永遠不放棄自己的理想,做一份自己喜愛的事業,擁有快樂和成就...

未來我們可以和性愛機器人結婚嗎?

你想體驗機器人性愛嗎?你想和性愛機器人結婚嗎?如果你想,機器人有拒絕你的權利嗎? 近日,第二屆“國際人類-機器人性愛研討會”大會在倫敦金史密斯大學落下帷幕。而...

全球最變態的十個地方

10.土耳其地下洞穴城市 變態指數:★★☆☆☆ 這是土耳其卡帕多西亞的一個著名景點,傳說是當年基督教徒們爲了躲避戰爭而在此修建。裏面曾住著20000人,...

科學家稱,人類死亡後意識將在另外一個宇宙中繼續存活

據英國《每日快報》報道,一位科學家兼理論家Robert Lanza博士宣稱,世界上並不存在人類死亡,死亡的只是身體。他認爲我們的意識借助我們體內的能量生存,而且...

《屏裏狐》片頭曲《我愛狐狸精》歌詞是什麽?

《我愛狐狸精》 - 劉馨棋   (電視劇《屏裏狐》主題曲)   作詞:金十三&李旦   作曲:劉嘉   狐狸精 狐狸仙   千年修...

 
 
 
<?PHP /** * patServer * PHP socket server base class * Events that can be handled: * * onStart * * onConnect * * onConnectionRefused * * onClose * * onShutdown * * onReceiveData * * @version 1.1 * @author Stephan Schmidt <[url=mailto:schst@php-tools.de]schst@php-tools.de[/url]> * @package patServer */ class patServer{ /** * information about the project * @var array $systemVars */ var $systemVars = array( "appName" => "patServer", "appVersion" => "1.1", "author" => array("Stephan Schmidt <[url=mailto:schst@php-tools.de]schst@php-tools.de[/url]>", ) ); /** * port to listen * @var integer $port */ var $port = 10000; /** * domain to bind to * @var string $domain */ var $domain = "localhost"; /** * maximum amount of clients * @var integer $maxClients */ var $maxClients = -1; /** * buffer size for socket_read * @var integer $readBufferSize */ var $readBufferSize = 128; /** * end character for socket_read * @var integer $readEndCharacter */ var $readEndCharacter = "\n"; /** * maximum of backlog in queue * @var integer $maxQueue */ var $maxQueue = 500; /** * debug mode * @var boolean $debug */ var $debug = true; /** * debug mode * @var string $debugMode */ var $debugMode = "text"; /** * debug destination (filename or stdout) * @var string $debugDest */ var $debugDest = "stdout"; /** * empty array, used for socket_select * @var array $null */ var $null = array(); /** * all file descriptors are stored here * @var array $clientFD */ var $clientFD = array(); /** * needed to store client information * @var array $clientInfo */ var $clientInfo = array(); /** * needed to store server information * @var array $serverInfo */ var $serverInfo = array(); /** * amount of clients * @var integer $clients */ var $clients = 0; /** * create a new socket server * * @access public * @param string $domain domain to bind to * @param integer $port port to listen to */ function patServer( $domain = "localhost", $port = 10000 ){ $this->domain = $domain; $this->port = $port; $this->serverInfo["domain"] = $domain; $this->serverInfo["port"] = $port; $this->serverInfo["servername"] = $this->systemVars["appName"]; $this->serverInfo["serverversion"] = $this->systemVars["appVersion"]; set_time_limit( 0 ); } /** * set maximum amount of simultaneous connections * * @access public * @param int $maxClients */ function setMaxClients( $maxClients ){ $this->maxClients = $maxClients; } /** * set debug mode * * @access public * @param mixed $debug [text|htmlfalse] * @param string $dest destination of debug message (stdout to output or filename if log should be written) */ function setDebugMode( $debug, $dest = "stdout" ){ if( $debug === false ){ $this->debug = false; return true; } $this->debug = true; $this->debugMode = $debug; $this->debugDest = $dest; } /** * start the server * * @access public * @param int $maxClients */ function start(){ $this->initFD = @socket_create( AF_INET, SOCK_STREAM, 0 ); if( !$this->initFD ) die( "patServer: Could not create socket." ); // adress may be reused socket_setopt( $this->initFD, SOL_SOCKET, SO_REUSEADDR, 1 ); // bind the socket if([url=mailto:!@socket_bind]!@socket_bind[/url]( $this->initFD, $this->domain, $this->port ) ){ @socket_close( $this->initFD ); die( "patServer: Could not bind socket to ".$this->domain." on port ".$this->port." ( ".$this->getLastSocketError( $this->initFd )." )." ); } // listen on selected port if([url=mailto:!@socket_listen]!@socket_listen[/url]( $this->initFD, $this->maxQueue ) ) die( "patServer: Could not listen ( ".$this->getLastSocketError( $this->initFd )." )." ); $this->sendDebugMessage( "Listening on port ".$this->port.". Server started at ".date( "H:i:s", time() ) ); // this allows the shutdown function to check whether the server is already shut down $GLOBALS["_patServerStatus"] = "running"; // this ensures that the server will be sutdown correctly register_shutdown_function( array( $this, "shutdown" ) ); if( method_exists( $this, "onStart" ) ) $this->onStart(); $this->serverInfo["started"] = time(); $this->serverInfo["status"] = "running"; while( true ){ $readFDs = array(); array_push( $readFDs, $this->initFD ); // fetch all clients that are awaiting connections for( $i = 0; $i < count( $this->clientFD ); $i++ ) if( isset( $this->clientFD[$i] ) ) array_push( $readFDs, $this->clientFD[$i] ); // block and wait for data or new connection $ready = @socket_select( $readFDs, $this->null, $this->null, NULL ); if( $ready === false ){ $this->sendDebugMessage( "socket_select failed." ); $this->shutdown(); } // check for new connection if( in_array( $this->initFD, $readFDs ) ){ $newClient = $this->acceptConnection( $this->initFD ); // check for maximum amount of connections if( $this->maxClients > 0 ){ if( $this->clients > $this->maxClients ){ $this->sendDebugMessage( "Too many connections." ); if( method_exists( $this, "onConnectionRefused" ) ) $this->onConnectionRefused( $newClient ); $this->closeConnection( $newClient ); } } if( --$ready <= 0 ) continue; } // check all clients for incoming data for( $i = 0; $i < count( $this->clientFD ); $i++ ){ if( !isset( $this->clientFD[$i] ) ) continue; if( in_array( $this->clientFD[$i], $readFDs ) ){ $data = $this->readFromSocket( $i ); // empty data => connection was closed if( !$data ){ $this->sendDebugMessage( "Connection closed by peer" ); $this->closeConnection( $i ); }else{ $this->sendDebugMessage( "Received ".trim( $data )." from ".$i ); if( method_exists( $this, "onReceiveData" ) ) $this->onReceiveData( $i, $data ); } } } } } /** * read from a socket * * @access private * @param integer $clientId internal id of the client to read from * @return string $data data that was read */ function readFromSocket( $clientId ){ // start with empty string $data = ""; // read data from socket while( $buf = socket_read( $this->clientFD[$clientId], $this->readBufferSize ) ){ $data .= $buf; $endString = substr( $buf, - strlen( $this->readEndCharacter ) ); if( $endString == $this->readEndCharacter ) break; if( $buf == NULL ) break; } if( $buf === false ) $this->sendDebugMessage( "Could not read from client ".$clientId." ( ".$this->getLastSocketError( $this->clientFD[$clientId] )." )." ); return $data; } /** * accept a new connection * * @access public * @param resource &$socket socket that received the new connection * @return int $clientID internal ID of the client */ function acceptConnection( &$socket ){ for( $i = 0 ; $i <= count( $this->clientFD ); $i++ ){ if( !isset( $this->clientFD[$i] ) || $this->clientFD[$i] == NULL ){ $this->clientFD[$i] = socket_accept( $socket ); socket_setopt( $this->clientFD[$i], SOL_SOCKET, SO_REUSEADDR, 1 ); $peer_host = ""; $peer_port = ""; socket_getpeername( $this->clientFD[$i], $peer_host, $peer_port ); $this->clientInfo[$i] = array( "host" => $peer_host, "port" => $peer_port, "connectOn" => time() ); $this->clients++; $this->sendDebugMessage( "New connection ( ".$i." ) from ".$peer_host." on port ".$peer_port ); if( method_exists( $this, "onConnect" ) ) $this->onConnect( $i ); return $i; } } } /** * check, whether a client is still connected * * @access public * @param integer $id client id * @return boolean $connected true if client is connected, false otherwise */ function isConnected( $id ){ if( !isset( $this->clientFD[$id] ) ) return false; return true; } /** * close connection to a client * * @access public * @param int $clientID internal ID of the client */ function closeConnection( $id ){ if( !isset( $this->clientFD[$id] ) ) return false; if( method_exists( $this, "onClose" ) ) $this->onClose( $id ); $this->sendDebugMessage( "Closed connection ( ".$id." ) from ".$this->clientInfo[$id]["host"]." on port ".$this->clientInfo[$id]["port"] ); @socket_close( $this->clientFD[$id] ); $this->clientFD[$id] = NULL; unset( $this->clientInfo[$id] ); $this->clients--; } /** * shutdown server * * @access public */ function shutDown(){ if( $GLOBALS["_patServerStatus"] != "running" ) exit; $GLOBALS["_patServerStatus"] = "stopped"; if( method_exists( $this, "onShutdown" ) ) $this->onShutdown(); $maxFD = count( $this->clientFD ); for( $i = 0; $i < $maxFD; $i++ ) $this->closeConnection( $i ); @socket_close( $this->initFD ); $this->sendDebugMessage( "Shutdown server." ); exit; } /** * get current amount of clients * * @access public * @return int $clients amount of clients */ function getClients(){ return $this->clients; } /** * send data to a client * * @access public * @param int $clientId ID of the client * @param string $data data to send * @param boolean $debugData flag to indicate whether data that is written to socket should also be sent as debug message */ function sendData( $clientId, $data, $debugData = true ){ if( !isset( $this->clientFD[$clientId] ) || $this->clientFD[$clientId] == NULL ) return false; if( $debugData ) $this->sendDebugMessage( "sending: \"" . $data . "\" to: $clientId" ); if([url=mailto:!@socket_write]!@socket_write[/url]( $this->clientFD[$clientId], $data ) ) $this->sendDebugMessage( "Could not write '".$data."' client ".$clientId." ( ".$this->getLastSocketError( $this->clientFD[$clientId] )." )." ); } /** * send data to all clients * * @access public * @param string $data data to send * @param array $exclude client ids to exclude */ function broadcastData( $data, $exclude = array(), $debugData = true ){ if( !empty( $exclude ) && !is_array( $exclude ) ) $exclude = array( $exclude ); for( $i = 0; $i < count( $this->clientFD ); $i++ ){ if( isset( $this->clientFD[$i] ) && $this->clientFD[$i] != NULL && !in_array( $i, $exclude ) ){ if( $debugData ) $this->sendDebugMessage( "sending: \"" . $data . "\" to: $i" ); if([url=mailto:!@socket_write]!@socket_write[/url]( $this->clientFD[$i], $data ) ) $this->sendDebugMessage( "Could not write '".$data."' client ".$i." ( ".$this->getLastSocketError( $this->clientFD[$i] )." )." ); } } } /** * get current information about a client * * @access public * @param int $clientId ID of the client * @return array $info information about the client */ function getClientInfo( $clientId ){ if( !isset( $this->clientFD[$clientId] ) || $this->clientFD[$clientId] == NULL ) return false; return $this->clientInfo[$clientId]; } /** * send a debug message * * @access private * @param string $msg message to debug */ function sendDebugMessage( $msg ){ if( !$this->debug ) return false; $msg = date( "Y-m-d H:i:s", time() ) . " " . $msg; switch( $this->debugMode ){ case "text": $msg = $msg."\n"; break; case "html": $msg = htmlspecialchars( $msg ) . "<br />\n"; break; } if( $this->debugDest == "stdout" || empty( $this->debugDest ) ){ echo $msg; flush(); return true; } error_log( $msg, 3, $this->debugDest ); return true; } /** * return string for last socket error * * @access public * @return string $error last error */ function getLastSocketError( &$fd ){ $lastError = socket_last_error( $fd ); return "msg: " . socket_strerror( $lastError ) . " / Code: ".$lastError; } function onReceiveData($ip,$data){ $this->broadcastData( $data,array(), true ); } } $patServer = new patServer(); $patServer->start(); ?>
󰈣󰈤
 
 
 
  免責聲明:本文僅代表作者個人觀點,與王朝網路無關。王朝網路登載此文出於傳遞更多信息之目的,並不意味著贊同其觀點或證實其描述,其原創性以及文中陳述文字和內容未經本站證實,對本文以及其中全部或者部分內容、文字的真實性、完整性、及時性本站不作任何保證或承諾,請讀者僅作參考,並請自行核實相關內容。
 
 
小龍女彤彤之情溢皇都
龔潔
智能手機形象美女
崔潔彤
回家的路上----
中國一站(哈爾濱)
清明植物園的花。
桃花堤印象之豎版
 
>>返回首頁<<
 
 
 
 熱帖排行
 
 
 
 
© 2005- 王朝網路 版權所有