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

<?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
聊天室
socket php建立聊天室、使用socket建立聊天室、php websocket 聊天室、php socket 聊天室、socket.io php 聊天室,以便于您获取更多的相关知识。

时间: 2025-01-03 07:43:23

用PHP的Socket建立自己的聊天室服务器的相关文章

Unity3D实现基于Socket通讯的公共聊天室

多个客户端一同使用就是一个简单的公共聊天室.服务端为一个控制台程序使用C#实现,当然,在Unity3D中也相应地使用了C#语言实现客户端,服务端和客户端能实现消息的互通,当服务端接收到某客户端发送过来的消息时将会对客户端列表成员进行广播,这是公共聊天室的最基本的形式.Socket通讯是网络游戏最为基础的知识,因此这个实例能向有志投身于网游行业的初学者提供指导意义. using System; using System.Collections.Generic; using System.Linq;

一个node+express+socket.io开发的聊天室源码

首先是下载包: npm install express npm install socket.io 建立文件:   开发的聊天室源码-express socket聊天室">   服务器端代码:server.js    代码如下 复制代码 var http=require("http"); var express=require("express"); var sio=require("socket.io"); var app=ex

nodejs+socket创建简单的聊天室例子

注:部分引用es6的写法,聊天室很简单,就是创建room,更改名称,简单聊天等功能! 命令:  /nick 用户名    //修改用户名  /join 房间名   //修改房间名称 入口文件server.js const http = require("http"); const fs = require("fs"); const path=require("path"); const mime=require("mime")

Python Socket 编程——聊天室示例程序

原文:Python Socket 编程--聊天室示例程序 上一篇 我们学习了简单的 Python TCP Socket 编程,通过分别写服务端和客户端的代码了解基本的 Python Socket 编程模型.本文再通过一个例子来加强一下对 Socket 编程的理解. 聊天室程序需求 我们要实现的是简单的聊天室的例子,就是允许多个人同时一起聊天,每个人发送的消息所有人都能接收到,类似于 QQ 群的功能,而不是点对点的 QQ 好友之间的聊天.如下图: 图来自:http://www.ibm.com/de

Android 基于Socket的聊天室实例_Android

Socket是TCP/IP协议上的一种通信,在通信的两端各建立一个Socket,从而在通信的两端之间形成网络虚拟链路.一旦建立了虚拟的网络链路,两端的程序就可以通过虚拟链路进行通信. Client A  发信息给 Client B ,  A的信息首先发送信息到服务器Server ,Server接受到信息后再把A的信息广播发送给所有的Clients 首先我们要在服务器建立一个ServerSocket ,ServerSocket对象用于监听来自客户端的Socket连接,如果没有连接,它将一直处于等待

nodejs写的聊天室chome一直在报错求解

问题描述 nodejs写的聊天室chome一直在报错求解 写了一个聊天室,但是chrome控制台一直在报错,这是我的项目目录:html部分代码 <!DOCTYPE html><html> <head> <meta charset=""utf-8"" /> <title></title> <link rel=""stylesheet"" href=&q

基于LINUX的多功能聊天室

原文:基于LINUX的多功能聊天室 基于LINUX的多功能聊天室 其实这个项目在我电脑已经躺了多时,最初写完项目规划后,我就认认真真地去实现了它,后来拿着这个项目区参加了面试,同样面试官也拿这个项目来问我,当然我是做过一遍了,而且为了面试,我将什么strcpy,strlen等最常用的函数都自己实现了一遍,说着,我感觉自己有点挺用功的样子呢! 后来,工作也定下来了,等三方,然后继续帮助我的导师做项目,经过老师的威逼利诱下,我屈服了,又把智能家居系统作为项目,同时也是我的毕业设计,而且功能还要十分完

用ASP程序组建基于WWW的聊天室

程序|聊天室|聊天室 在网上的各种实时联络方式中,基于WWW的聊天室恐怕是最方便的了:它只需一次性地在服务器端安装成功,客户端使用Windows自带的IE浏览器就可以随意访问了,而不再另外添加第三方软件. ASP程序聊天室V2.5就是这样一款由ASP程序编制成的基于WWW的聊天室服务器端软件,作者是江苏省东台市的姜军,为简体中文版的共享软件(注册费用是给作者寄一张贺卡或5元钱去),功能较齐全,支持用户注册.资料修改.分用户等级(以用户在线总时间来分).私聊.留言.发言的历史记录.新留言提示.禁止

用ASP建造自己的聊天室

聊天室|聊天室 聊天室想必你一定去过吧,但想不想建立自己的聊天室呢?其实这一点都不难,Active Server Script提供了Application对象和Session对象,Application对象代表了一个Active Server应用程序,也就是一个Web网页,Session对象则表示一个用户,代表一个用户对这个页面的一次访问,通过Application对象可以让访问它的所有用户共享信息,并可以在Web服务器运行期间持久地保存数据,而Session对象也可以在用户的一次访问期间持久地