1. First install the Swoole extension Swoole-1.x which requires PHP-5.3.10 or later swoole-2.x which requires phP-7.0.0 or later
The company environment is PHP5.6.31, so it is more troublesome to compile and install, 7 directly use the command (pecl install swoole)
Wget https://github.com/swoole/swoole-src/archive/v1.10.1.tar.gz tar – ZXVF v1.10.1. Tar. Gz CD swoole SRC – 1.10.1 phpize ./configure –with-php-config=/usr/local/php/bin/php-config make && make install
Then add the swoole.so extension to php.ini 2. PHP artisan make: Command Swoole # Create a command Swoole and add a file in app/Console/Commands
Commands\Swoole::Class # add command list 3 to kernel. PHP. 1. Edit the swoole.php file in app/Console/Command
<? php namespace App\Console\Commands; use Illuminate\Console\Command; class Swoole extends Command { public$ws;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'swoole {action? } ';
/**
* The console command description.
*
* @var string
*/
protected $description = 'swoole';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$action = $this->argument('action');
switch ($action) {
case 'close':
break;
default:
$this->start();
break;
}
}
public function start() {// Create a WebSocket server object and listen on port 0.0.0.0:9502$this->ws = new \swoole_websocket_server("0.0.0.0", 9502); // Listen for WebSocket connection opening events$this->ws->on('open'.function ($ws.$request) {
var_dump($request->fd . "Connection successful");
// $ws->push($request->fd, "hello, welcome\n"); }); // Listen for WebSocket message events$this->ws->on('message'.function ($ws.$frame{/ /echo "Message: {$frame->data}\n";
// $ws->push($frame->fd, "server: {$frame->data}");
// var_dump($ws->connection_info($frame->fd)); //fd binds the id uid passed by the client$ws->bind($frame->fd, $frame->data);
});
$this->ws->on('request'.function ($request.$response) {// Get parameters from POST after receiving HTTP request // get all connected clients, verify uid push message to specified user // token verify push source, avoid malicious accessif ($request->post['token'] = =# # #) {
$clients = $this->ws->getClientList();
$clientId = [];
foreach ($clients as $value) {
$clientInfo = $this->ws->connection_info($value);
if (array_key_exists('uid'.$clientInfo) && $clientInfo['uid'] = =$request->post['s_id']) {
$clientId[] = $value; }}if(! empty($clientId)) {
foreach ($clientId as $v) {
$this->ws->push($v.$request->post['info']); }}}}); // Listen for WebSocket connection closure events$this->ws->on('close'.function ($ws.$fd) {
echo "client:{$fd} is closed\n";
});
$this->ws->start(); }} [note] The onRequest event of httpServer is used to notify the instance of web end by using curl when uploading data. If there is a better way to trigger real-time active push by the server in the future, the onRequest event of HttpServer is used. 2. Edit HTML <div id="test">
<a href="javascript:void(0)"> Run websocket</a> </div> $'#test').click(function() {if("WebSocket" in window){
console.log("Your browser supports WebSocket \n");
var ws = new WebSocket(Ws: / / 66.66.66.66:9502 ""); // Create the websocket object ws.onOpen =function(){
// ws.send("Connection established \n");
ws.send($("#content").attr("js-sid"));
console.log("Data in transit");
}
ws.onmessage = function(evt){
var recv_msg = evt.data;
console.log("The data received are :"+recv_msg);
}
ws.onerror = function(evt,e){
console.log("Error message is"+e);
}
ws.onclose = function(){
console.log("Connection closed"); }}else{
console.log("Your browser does not support websocket\n"); }}); Curl curl curl curl curl curl curl curl curl curl curlfunction swooletest($param = ['s_id'= > 2,'info'= >'info'])
{
$param['token'] = # # #;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:9502");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1); // Set the POST data$post_data = $param;
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_exec($ch);
curl_close($ch); } 4. During the test, directly run the PHP artisan swoole command in the artisan directory of Laravel to start the socket service, then run the client on the page, and finally call curl to push the data. 4. After success, use the Supervisor swoole command or nohup background startup. The supervisor configuration is troublesome but can be restarted automatically. Nohup resolve the nohup PHP artisan swoole & with a command# one command solution1. Here I use isbindWhen you want to send data to a client, send a UID to the fd, and then bind the UID to the FD while the server processes it. When you want to send data to a client, send a UID to the FD. But here I'm using connection_info to check by iterating through all the (poorly) connected users of getClientList. Curl = curl = curl = curl = curl = curl = curl = curl = curl = curl = curl 3. Convert the pushed information to JSON and then send it, that is, info value 4. The account in this example may be logged in from multiple terminals and have multiple FD bound uuIds, so iterate over pushCopy the code
To read the article, visit www.zxb8.cc/?p=515