老雷socket编程之php利用socket扩展实现聊天服务
socket聊天服务原理
php有两个socket的扩展 sockets和streams
sockets
socket_create(af_inet, sock_stream, sol_tcp)
socket_write
socket_read
socket_clo
客户端
socket_connect($socket, $address, $rvice_port);
服务端
socket_bind($sock, $address, $port)
socket_listen($sock)
socket_accept
streams
客户端
stream_socket_client
fwrite
fread
fclo($fp);
服务端
stream_socket_rver
stream_t_blocking
stream_lect
stream_socket_accept conn
stream_socket_recvfrom
stream_socket_ndto
stlike的过去式ream_socket_shutdown
课后练习
使用sockets和streams扩展实现客户端跟服务端的功能。
服务端代码 客服端可使用udp&tcp测试工具
<?phpclass考研英语班辅导 socketrvice{public $host="tcp://0.0.0.0:8000"; private $address; private $port; private $_sockets;public $clients;public $maxid=1000; public function __construct($address = '', $port='') { if(!empty($address)){ $this->address = $address; 察觉近义词 } if(!empty($port)) { $this-商业地产运营模式>port = $port; } }public function onconnect($client_id){echo "client client_id:{$client_id} \n"; }public function onmessage($client_id,$msg){//发给所有的foreach($this->clients as $kk=>$cc){if($kk>0){$this->nd($cc, $msg);}}}public function onclo($client_id){echo "$client_id clo \n";} public function rvice(){ //获取tcp协议号码。 $tcp = getprotobyname("tcp"); $sock = stream_socket_rver($this->host, $errno, $errstr);; if(!$sock) { throw new exception("failed to create socket: ".socket_strerror($sock)."\n"); }stream_t_blocking($sock,0); $this->_sockets = $sock; echo "listen on $this->address $this->host ... \n"; } public function run(){ $this->rvice(); $this->clients[] = $this->_sockets; while (true){ $changes = $this->clients; //$write = null; //$except = null; stream环保小卫士_lect($changes, $write, $except, null); foreach ($changes as $key => $_sock){ if($this->_sockets == $_sock){ //判断是不是新接入的socket if(($newclient = stream_socket_accept($_sock)) === fal){unt($this->clients[$key]);continue; } $line = trim(stream_socket_recvfrom($newclient, 1024)); $this->maxid++; $this->clients[$this->maxid] = $newclient; $this->onconnect($this->maxid); } el {$msg=@stream_socket_recvfrom($_sock, 2048);if(!$msg){stream_socket_shutdown($this->clients[$key],stream_shut_rdwr);unt($this->clients[$key]);$this->onclo($key);}el{$msg=$this->decode($msg);$this->onmessage($key,$msg);} } } } } /** * 发送数据 * @param $newclinet 新接入的socket * @param $msg 要发送的数据 * @return int|string */ public function nd($newclinet, $msg){$msg=$this->encode($msg);if($msg){stream_socket_ndto($newclinet, $msg);} } public function encode($msg){ return $msg . "\n";}public function decode($msg){return rtrim($msg, "\r\n");} /** * 关闭socket */ public function clo(){ return socket_clo($this->_sockets); }} $sock = new socketrvice('127.0.0.1','9000');$sock->run();
本文发布于:2023-04-07 06:51:08,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/b3ec4e009b4bb23c5ef6566375e1add1.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:老雷socket编程之PHP利用socket扩展实现聊天服务.doc
本文 PDF 下载地址:老雷socket编程之PHP利用socket扩展实现聊天服务.pdf
留言与评论(共有 0 条评论) |