Build your own chat room server _php tutorial with PHP socket

Source: Internet
Author: User
Tags stephan schmidt

/**
* Patserver
* PHP Socket Server base class
* Events that can be handled:
* * OnStart
* * OnConnect
* * onconnectionrefused
* * OnClose
* * OnShutdown
* * Onreceivedata
*
* @version 1.1
* @author Stephan Schmidt
* @package Patserver
*/
Class patserver{
/**
* Information about the project
* @var Array $systemVars
*/
var $systemVars = Array (

"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 integer $readEndCharacter
*/
var $readEndCharacter = "";

/**
* 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 is 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
*/
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 is 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 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 was already shut down
$GLOBALS ["_patserverstatus"] = "Running";
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 that 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 for incoming data
for ($i = 0; $i < count ($this->clientfd); $i + +) {<

http://www.bkjia.com/PHPjc/508269.html www.bkjia.com true http://www.bkjia.com/PHPjc/508269.html techarticle ? PHP/** * patserver * PHP Socket Server base class * Events that can be handled: * * OnStart * * onConnect * * Onconnectio nrefused * * OnClose * * OnShutdown * * onreceivedata * * ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.