PHP socket implementation of the chat room code sharing, socket chat room
/*** patserver* PHP Socket Server base class* Events that can be handled:* * onstart* * onconnect* * onconnectionrefuse d* * onclose* * onshutdown* * onreceivedata** @version 1.1* @author Stephan Schmidt
* @package patserver*/class Patserver {/*** information about the project* @var array $systemVars */var $systemVars = Arra Y ("appName" = "Patserver", "appversion" = "1.1", "author" = = Array ("Stephan Schmidt
/*** 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 Integ ER $readEndCharacter */var $readEndCharacter = "\ n";/*** maximum of backlog in queue* @var integer $maxQueue */var $maxQ Ueue = 500;/*** Debug mode* @var boolean $debug */var $debug = true;/*** Debug mode* @var string $debugMode */var $debu Gmode = "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 is stored here* @var a Rray $clientFD */var $clientFD = array ();/*** needed to store client information* @var Array $clientInfo */var $clientIn fo = array ();/*** needed To store server information* @var array $serverInfo */var $serverInfo = array ();/*** amount of clients* @var integer $c lients*/var $clients = 0;/*** Create a new socket server** @access public* @param string $domain domain to bind to* @p Aram integer $port port to listen to*/function patserver ($domain = "localhost", $port = 10000) {$this->domain = $d Omain; $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 ($max Clients) {$this->maxclients = $maxClients;} /*** set Debug mode** @access public* @param mixed $debug [text|htmlfalse]* @param string $dest destination of debug Messa GE (stdout to output or filename if log shouldbe 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_i NET, Sock_stream, 0); if (! $this->initfd) die ("Patserver:could not create socket."); Adress may 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 list En (". $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 was already shut down $GLOBALS ["_patserverstatus"] = "Run Ning "; This ensures, the server would 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 This is 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 to 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 is 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 an integer $clientId internal ID of the client to read from* @r Eturn string $data data that is Read*/function Readfromsocket ($clientId) {//start with empty string $data = ""; Read data from the 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_a Ccept ($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 $conn ected true if client is connected, false otherwise*/functionIsConnected ($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 closeconnecti On ($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 () {retur n $this->clients;} /*** send data to a client** @access public* @param int $clientId ID of the client* @param string $data data to send* @p Aram Boolean $debugData flag to indicate whether data, written to socket should also be sent as debug Message*/func tion 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. "' CLI Ent ". $clientId." (". $this->getlastsocketerror ($this->clientfd[$clientId])."); /*** send data to all clients** @access public* @param string $data the 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->clie ntfd[$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). "
\ 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 the last socket error** @access public* @return A 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 ();
Make a chat room with a PHP socket
Why bother? PHP production chat room, the key technology is the page local automatic refresh.
With PHP Ajax technology, you can achieve your requirements perfectly.
The specific principle of the following, in the web chat box, the AJAX call, Ajax pass parameters of a PHP page, this page calls the database at the same time, the new content in the database to return to the page chat box.
Then you can make your own time, is 20 seconds to access the database, or 10 seconds to access the database.
As for PHP socket technology, to tell you the truth, I have been in contact with PHP for 8 years, have not touched.
I think the key is not to use what technology, the key is to solve the problem.
Hope is useful to you.
Private chat in a php chat room write code
PHP support for network communication is not very good, PHP socket although support, but the concurrency is not good. Or use Java's Mina framework.
http://www.bkjia.com/PHPjc/864934.html www.bkjia.com true http://www.bkjia.com/PHPjc/864934.html techarticle PHP Socket implementation of the chat room code sharing, socket chat room/*** patserver* PHP socket Server base class* Events that can be handled:* * onstart* * onconnect* * onconnectionrefused* ...