Foreword: Swoole is a production-oriented PHP asynchronous communication framework written in C language. It has a wide range of uses in practical work. Now I recommend its installation and simple and practical methods to everyone, hoping to help everyone in their work.
1. Install the swoole service
-
Download swoole source code, download address: https://github.com/swoole/swoole-src/releases
-
Upload the tar package to /usr/local/src/swoole, where the installation source files are stored
-
Unzip the source file, tar –xvfswoole.tar
-
Go to the directory you just decompressed and enter the command phpize
-
Note: phpize is something in php-devel, it can add extensions to PHP dynamically, so make sure you have the php-devel package installed on your machine
-
Then, enter the following commands in turn: ./configure, execute the compilation detection make, and compile swoole
-
Lack of pcre and pcre-devel related packages, just install them
-
sudo make install
-
After php.ini is compiled and installed successfully under etc, we also need to modify php.ini and add the swoole.so extension to it
-
extension=swoole.so
-
Enter php -m to see the swoole, indicating that the extension is installed successfully.
Second, install apache to start the swoole service
-
Test whether the installation is correct and start the swoole Php service
-
Add the server.php file and client.php file to apache. The general directory is under var/www/html
-
Open two terminals and open these two files under the directory where the two files are located, you can realize the socket long connection service
Install lsof: yum -y install lsof
Third, configure the server side
class WebSocketService {
private static $instance = NULL;
public $tagindex = 0;
public $server = null;
public $office_cache = null;
public $timer_arr = []; //该变量保存所有的定时器任务ID,每一个客户端可以通过$timer_arr[客户端ID]得到该客户端建立的所有定时器
public $conf = [
'host' => '0.0.0.0',
'port' => 9999, //服务使用端口
'worker_num' => 2, //启动worker进程数
'task_worker_num' => 8, //启动task进程数
'is_daemonize' => 0, //是否后台运行:0-否,1-是
'log_file' =>'/tmp/swoole_webSocket_server.log', //日志文件路径
'abc' =>0,
];
public function getTagIndex() {
return $this->conf['abc'];
}
public function setSetTagIndex($index) {
$this->conf['abc'] = 100;
echo $this->getTagIndex();
}
public function __construct($config = []) {
$this->office_cache = array('1' => '1', '3'=>'2');
$this->conf = array_merge($this->conf, (array)$config);
}
//静态方法,返回此类唯一实例
public static function getInstance(){
if(empty(self::$instance)){
echo "instance \n";
self::$instance=new WebSocketService();
}
return self::$instance;
}
/**
* 服务器端运行webSocket的入口
*/
public function run() {
try {
$this->server = new \swoole_websocket_server($this->conf['host'],$this->conf['port']);
$this->server->set(
[
'worker_num' => $this->conf['worker_num'],
'task_worker_num' =>$this->conf['task_worker_num'],
'daemonize' => $this->conf['is_daemonize'],
'log_file' => $this->conf['log_file'],
]
);
//注册方法列表
$this->server->on('open', [$this, 'open']);
$this->server->on('message', [$this, 'message']);
$this->server->on('task', [$this, 'task']);
$this->server->on('finish', [$this, 'finish']);
$this->server->on('close', [$this, 'close']);
$this->server->start();
} catch (\Exception $e) {
var_dump($e->getCode() . ':' . $e->getMessage());
}
}
/**
* 建立socket链接时,执行方法
* @param $server
* @param $request
*/
public function open($server, $request) {
$data = [
'client_id' => $request->fd,
'request' => $request
];
echo 'open<<'.$data['client_id'];
$this->doOpen($data);
}
/**
* 发送消息时,执行方法
* @param $server
* @param $frame
*/
public function message($server, $frame) {
echo "GET_mesage\n";
$data = [
'client_id' => $frame->fd,
'data' => $frame->data,
'frame' => $frame,
];
$this->doMessage($data);
}
/**
* 执行具体任务
* @param $server
* @param $task_id
* @param $from_id
* @param $data
*/
public function task($server, $task_id, $from_id, $data) {
$data['task_id'] = $task_id;
$data['from_id'] = $from_id;
$this->doTask($data);
}
/**
* 任务结果处理
* @param $server 服务器对象
* @param $taskId 任务进程ID
* @param $data
*/
public function finish($server, $taskId, $data) {
$data['task_id'] = $taskId;
$this->doFinish($data);
}
/**
* 关闭链接
* @param $server 服务器对象
* @param $client_id 客户端唯一标识
*/
public function close($server, $client_id) {
$data = [
'client_id' => $client_id
];
$this->doClose($data);
}
/**
* 客户端成功连接到服务器时,会触发该方法
* 子类根据需求重写该方法
* @param $data
* [
* 'client_id', //客户端唯一标识
* 'data', //一些请求数据
* 'frame', //swoole的数据
* ];
*/
public function doOpen($data) {
echo "建立连接成功";
}
/**
* 得到Swoole Websocket Server
*
* @return null|\swoole_websocket_server
*/
public function getServer()
{
return $this->server;
}
/**
* 收到客户端发来的消息,会触发该方法
* 子类根据需求重写该方法
* @param $data
* [
* 'client_id', //客户端唯一标识
* 'data', //客户端发送过来的消息(数据)
* 'frame', //swoole的数据
* ];
*/
public function doMessage($data) {
$info = json_decode($data['data'],true);
$officeid = $info['officeid'];
$client_id = $data['client_id'];
echo"<<<<".$officeid.">>>>".$client_id."\r\n";
if ($officeid == 1) {
$this->sendMsgToClient('2',array('msg' =>'我是1号场地发送给你数据'));
} else {
$this->sendMsgToClient('1',array('msg' =>'我是3号场地发送给你数据'));
}
}
/**
* 具体的工作任务。需要通过 $this->doJob()来触发
* 子类根据需求重写该方法
* @param $data
* [
* 'client_id', //客户端唯一标识
* ];
*/
public function doTask($data) {
}
/**
* 工作的结果处理。
* 子类根据需求重写该方法
* @param $data
* [
* 'client_id', //客户端唯一标识
* ];
*/
public function doFinish($data) {
}
/**
* 客户端断开时会自动触发该方法
* 子类根据需求重写该方法
* @param $data
* [
* 'client_id', //客户端唯一标识
* ];
*/
public function doClose($data) {
}
/**
* 发送任务
* @param $data 必须是数组,且要有$data['client_id']
*/
public function doJob($data) {
$this->server->task($data);
}
public function finishJob($data) {
$this->server->finish($data);
}
/**
* 发送消息到客户端
* @param $client_id
* @param $msg
*/
public function sendMsgToClient($client_id, $msg) {
echo "发送信息给客户端:{$client_id} | {$msg['action']['name']} | " . date('Y-m-dH:i:s') . "\r\n";
$this->server->push($client_id, json_encode($msg));
}
/**
* 关闭客户端链接
* @param $client_id
*/
public function closeClient($client_id) {
$this->server->close($client_id);
}
/**
* 添加定时器
* @param $client_id
* @param $tick_time
*/
public function addTimer($client_id, $tick_time) {
//暂未实现,先使用swoole原生写法
}
/**
* 清除定时器
* @param $client_id
* @param $arr
*/
public function clearTimer($client_id, &$arr) {
if (is_array($arr)) {
foreach ($arr[$client_id] as $val) {
if (is_array($val)) {
foreach ($val as $v) {
swoole_timer_clear($v);
}
} else {
swoole_timer_clear($val);
}
}
}
unset($arr[$client_id]);
}
}
Fourth, configure the html front end
$(document).ready(function(){
varwsurl = "ws://182.92.101.206:9999/";
console.log(wsurl);
varwebsocket = new WebSocket(wsurl);
websocket.onopen= function(evt){
console.log('Server: 打开WebSocket连接');
};
websocket.onclose= function(evt){
console.log('Server: 关闭WebSocket连接');
};
websocket.onmessage= function(evt){
varres = JSON.parse(evt.data);
console.log('Server: 收到消息(来自:'+res+'请求)');
console.log(res);
};
websocket.οnerrοr= function(evt){
console.log('Server: 出现错误');
console.log(evt.data);
}
functiondoSend(msg){
console.log('Client:发送消息 ' + msg);
websocket.send(msg);
}
});
五、启动start.php文件,cd到指定目录下,然后PHP-CLI运行php start.php。
这种方式是没有启用线程保护的关掉后程序结束线程还在占用。
require 'src/WebSocketSwoole/WebSocketService.php';
// require './WebSocketService.php';
session_start();
// $demoService = new\WebSocketSwoole\WebSocketService();
$demoService =\WebSocketSwoole\WebSocketService::getInstance();
$demoService->run();
*声明:本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜。
END
PHP开源社区 扫描关注 进入”PHP资料“
免费获取进阶
面试、文档、视频资源