Home > Backend Development > PHP Tutorial > Analysis: Implementing a simple chat program through php socket and using telnet_PHP tutorial

Analysis: Implementing a simple chat program through php socket and using telnet_PHP tutorial

WBOY
Release: 2016-07-21 15:06:04
Original
883 people have browsed it

The following is a simple message processing server implemented through PHP's socket extension module: bind to a local port, listen for client connections, receive data and forward it to all clients except the sender
socket_server.php

Copy code The code is as follows:

#!/usr/bin/env php
//author:zhxia
if(!extension_loaded('sockets')){
die('the sockets extension is not loaded!');
}
const PORT=9981;
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP) or die('socket create error!');
#Reuse the port by setting this option
socket_set_option ($socket,SOL_SOCKET,SO_REUSEADDR,1);
socket_bind($socket,0,PORT);
socket_listen($socket);
#Use non-blocking mode
socket_set_nonblock($socket);
echo 'listen on port '.PORT.'...'.PHP_EOL;
$clients=array($socket);
while(TRUE){
$read=$clients;
$write=$except=array();
//Detect whether the socket status changes through the select system call
if(socket_select($read,$write,$except,0)<1) {
continue;
}
//Detect if there is a client to connect
if(in_array($socket,$read)){
$clients[]=$newsocket=socket_accept ($socket);
socket_write($newsocket,"welcome!nthere are ".(count($clients)-1)." client heren");
socket_getpeername($newsocket,$ip);
echo "new client connected:$ipn";
$key=array_search($newsocket,$read);
unset($read[$key]);
}

foreach($read as $read_socket){
$data=@socket_read($read_socket,1024,PHP_NORMAL_READ);
if($data===false){
//If not fetched To the data, it means that the client has disconnected
$ key = array_search ($ read_sockets, $ clients);
unset ($ clients [$ key]);
echo "client disconnectd.n"; continue;
}
$data=trim($data);
if(!empty($data)){
foreach($clients as $write_socket){
                    // Exclude the server and itself, and then send the data to all other clients
if($write_socket==$socket||$write_socket==$read_socket){
continue;
}
socket_write ($write_socket, "$datan" ); :

zhxia@zhxia-pc:~/sh/php$ ./socket_server.php
listen on port 9981...


Connected via telnet:

zhxia@haozudb:~$ telnet 192.168.187.16 9981
Trying 192.168.187.16...Connected to 192.168.187.16.
Escape character is '^]'.
welcome!
there are 1 client here


http://www.bkjia.com/PHPjc/327639.html

www.bkjia.com

true

http: //www.bkjia.com/PHPjc/327639.html

TechArticle

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template