PHP

首页 -  PHP  -  laravels实现WebSocket,IM通讯

laravels实现WebSocket,IM通讯

laravels实现WebSocket,IM通讯

1.安装laravels

composer require hhxsv5/laravel-s

php artisan laravels publish

2.如果安装缺少扩展config.json下添加配置

"config": {
    "platform": {
        "ext-pcntl": "7.3",
        "ext-posix": "7.3"
    }
}

3.上代码

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/9/27
 * Time: 17:41
 */

namespace App\Service;


use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Illuminate\Support\Facades\Log;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;

class WebSocketService implements WebSocketHandlerInterface
{
    //https://github.com/wenzhizhong/chatce 别人的聊天系统
    public function __construct()
    {

    }

    public function onOpen(Server $server, Request $request)
    {
        // 在触发onOpen事件之前,建立WebSocket的HTTP请求已经经过了Laravel的路由,
        // 所以Laravel的Request、Auth等信息是可读的,Session是可读写的,但仅限在onOpen事件中。
        // \Log::info('New WebSocket connection', [$request->fd, request()->all(), session()->getId(), session('xxx'), session(['yyy' => time()])]);
        Log::info('WebSocket 连接建立'.$request->fd);
        Log::info('WebSocket 连接建立');
        $server->push($request->fd, 'Welcome to LaravelS');
        // throw new \Exception('an exception');// 此时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
    }
    public function onMessage(Server $server, Frame $frame)
    {
        // \Log::info('Received message', [$fram        // \Log::info('Received message', [$frame->fd, $frame->data, $frame->opcode, $frame->finish]);
        //
        //        $server->push($frame->fd, $frame->data);e->fd, $frame->data, $frame->opcode, $frame->finish]);


        //发给一个人
        //$server->push($frame->fd, $frame->data);

        //发给所有用户
        $list = $server->getClientList();

        Log::info('WebSocket 连接建立消息list'.json_encode($list));

        foreach ($list as $row){

            //$server->close($row);

            Log::info('fd'.$row);
            Log::info('fff'.$frame->fd);

            @$server->push($row, $frame->data);
        }





        Log::info('WebSocket 连接建立消息FD'.$frame->fd);
        Log::info('WebSocket 连接建立消息Data'.$frame->data);
//        $arr = [
//            'time' => date('Y-m-d H:i:s')
//        ];
//        $server->push($frame->fd, json_encode($arr));
        // throw new \Exception('an exception');// 此时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
    }

    public function onClose(Server $server, $fd, $reactorId)
    {
        Log::info('WebSocket 连接关闭--'.$fd);
        Log::info('WebSocket 连接关闭');
        // throw new \Exception('an exception');// 此时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
    }


}

4.html端

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Chat Client</title>
</head>
<body>
<div style="width:600px;margin:0 auto;border:1px solid #ccc;">
    <div id="content" style="overflow-y:auto;height:300px;"></div>
    <hr />
    <div style="height:40px;background:white;">
        <input type="text" class="form-control" id="message"  placeholder="请输入内容">
        <button type="button" class="btn btn-primary" onclick="sendMessage()">Primary</button>
    </div>
</div>

<script type="text/javascript">
    // 端口和ip地址对应不要写错
    //var webSocket = new WebSocket("ws://172.16.0.100:5201");
    var webSocket = new WebSocket("ws://172.16.0.100/dctrl/ws");
    webSocket.onopen = function (event) {
        console.log('webSocket 连接成功');
    };
    // 连接关闭时触发
    webSocket.onclose = function (event) {
        console.log("WebSocket 关闭连接");
    }

    //收到服务端消息回调
    webSocket.onmessage = function (event) {
        var content = document.getElementById('content');
        content.innerHTML = content.innerHTML.concat('<p style="margin-left:20px;height:20px;line-height:20px;">'+event.data+'</p>');
        console.log(event.data)
    }

    var sendMessage = function(){
        var data = document.getElementById('message').value;
        webSocket.send(data);
    }
</script>


</body>
</html>

5.nginx配置我这用到的是docker容器

upstream swoole {
   #172.200.7.200:5200 php容器的laravels
   server 172.200.7.200:5200 weight=5 max_fails=3 fail_timeout=30s;
   keepalive 16;
}

 map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
 }

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;
    root /docker/www/lrms-2008/public;
    index index.php index.html;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /docker/www/lrms-2008/public;
    }

    location / {
        try_files $uri @laravels;
    }

    #用地址代理wss的ip和端口
    location  /dctrl/ws {
        proxy_pass http://172.16.0.100:5201;
        proxy_redirect   off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Origin "";
    }

    location @laravels {
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Real-PORT $remote_port;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header Scheme $scheme;
        proxy_set_header Server-Protocol $server_protocol;
        proxy_set_header Server-Name $server_name;
        proxy_set_header Server-Addr $server_addr;
        proxy_set_header Server-Port $server_port;
        proxy_pass http://swoole;
    }
}



(0)
分享:

本文由:xiaoshu168.com 作者:xiaoshu发表,转载请注明来源!

标签:

相关阅读