Note:

  1. If the site uses HTTPS, WebSocket must use the WSS protocol
  2. Connection requests using the WSS protocol must be written to domain names only, not IP+ port
  3. Implementing WSS through Nginx forwarding eliminates the need for WSS for internal communication

Nginx configuration

  1. Simply add a location to the SERVER configured with HTTPS
  2. Nginx reverse proxies, whether HTTP/S or WebSocket, go through port 443 and are distributed by Nginx to each project server
Location = /websocket {proxy_pass http://xxxx.cn:7303; proxy_redirect off; proxy_set_header Host www.xxx.cn:7303; Proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; #proxy_set_header x-real-ip $remote_addr; #proxy_set_header X-Forwarded-For $remote_addr; }Copy the code

Laravel

Server

<? php namespace App\Console\Commands; use Illuminate\Console\Command; class WebSocket extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'Web {action=start}'; /** * The console command description. * * @var string */ protected $description = 'WebSocket description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $arg = $this->argument('action'); switch ($arg) { case 'start': $this->info('WebSocket observer started'); $this->start(); break; }} public function start() {$server = new \swoole_websocket_server("0.0.0.0", 7303, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL); $server = new \swoole_websocket_server("0.0.0.0", 7303); $server->set('daemonize' => 1, 'daemonize' => 1, / / / / configure SSL certificate and key path 'ssl_cert_file' = > "/ data/PHP/cert/www.xxxxx.cn.pem", //'ssl_key_file' => "/data/php/cert/www.xxxxx.cn.key" ]); $server->on('Open', array($this, 'OnOpen')); $server->on('Message', array($this, 'OnMessage')); $server->on('Close', array($this, 'OnClose')); $server->start(); } public function OnOpen($server, $req) { echo "server: handshake success with fd {$req->fd}\n"; } public function OnMessage($server, $frame) { var_dump($frame); $this->send($server, $frame); } public function OnClose($server, $fd) { echo "client {$fd} closed \n"; } public function send($server, $frame) { $info = json_decode($frame->data, true); // var_dump(php_sapi_name()); switch ($info['action']) { case 'home': case 'device': case 'goodsError': case 'shopping': $conn_list = $server->connection_list(0, 100); if ($conn_list === false or count($conn_list) === 0) { echo "finish \n"; } foreach ($conn_list as $fd) { if ($fd ! = $frame->fd) { $arr = array("action" => $info['action'], "data" => $info['data']); $data = json_encode($arr); $server->push($fd, $data); } } break; }}}Copy the code

Client

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class WebClient extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SendSocket {data}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'WebClient description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $data = $this->argument('data');

        $cli = new \swoole_http_client('127.0.0.1', 7303);

        $cli->setHeaders(['Trace-Id' => md5(time()),]);

        $cli->on('message', function ($_cli, $frame) {
            var_dump($frame);
        });

        $cli->upgrade('/', function ($cli) use ($cli, $data) {
            $cli->push($data);
            $cli->close();
        });
    }
}
Copy the code

WEB

# address must add the/websocket let ws = new websocket (" wss://www.xxx.com: 7300 / websocket '); ws.onopen = function(evt) { console.log("Connection open ..." ); // ws.send("Hello WebSockets!" ); }; / / refresh operation specified in the specified page access to news ws. The onmessage = function (evt) {let hashValue = window. The location. The hash. The split ('/'); let hashLength = hashValue . length; let newKey = hashValue[hashLength - 1]; console . log("Received Message: " + evt . data); // ws.close(); let data = JSON . parse(evt . data); if (data.action === 'home' && newKey === '') { console . log('home-socket'); $this.homesocket (); } else if (data.action === 'home' && newKey === 'shoppingMonitor') {console.log('shopping-home-socket') // Shopping cart monitor $this.shoppingMonitorSocket(); } else if (data . action === 'shopping' && newKey === 'shoppingMonitor') { console.log('shopping-socket'); $this. ShoppingMonitorSocket (); } else if (data . action === 'goodsError') { console.log('goodsError-socket'); }} ws.onclose = function(e){// When the client receives the server to close the connection request, the onclose event console.log("close"); } ws.onerror = function(e){if (e){if (e){ws.onerror = function(e){if (e){ws.onerror = function(e){ }Copy the code