溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

用PHP+swoole做簡單的聊天室

發(fā)布時(shí)間:2020-08-03 16:08:58 來源:網(wǎng)絡(luò) 閱讀:10282 作者:阿澤Aze 欄目:web開發(fā)
最近自學(xué)了swoole,想做點(diǎn)東西試試看,剛好看到可以簡單做個(gè)聊天室,于是自己研究研究搞了一個(gè)。

websocket是不同于http的另外一種網(wǎng)絡(luò)通信協(xié)議,能夠進(jìn)行雙向通信,基于此,可開發(fā)出各種實(shí)時(shí)通信產(chǎn)品,我簡單做了個(gè)聊天室demo,順便分享一下。

這里我簡單把websocket服務(wù)器分配的fd(文件描述,可以理解為用戶id)在文本(user.txt),
然后進(jìn)行遍歷群發(fā)送消息,不啰嗦,核心代碼如下:
websocket.php
<?php
class Websocket
{
    public $server;
    public $userFile = __DIR__ . '/user.txt';
    public function __construct()
    {
        //設(shè)置成0.0.0.0代表監(jiān)聽所有地址來源的連接,所以可以進(jìn)行連接。
        $this->server = new swoole_websocket_server("0.0.0.0", 9502);

        //監(jiān)聽WebSocket連接打開事件
        $this->server->on('open', function (swoole_websocket_server $server, $request) {
            echo "server: handshake success with fd{$request->fd}\n";
            $array = [];
            if (file_exists($this->userFile)) {
                $array = array_filter(explode(',', file_get_contents($this->userFile)));
            }
            array_push($array, $request->fd);
            file_put_contents($this->userFile, join(',', $array), LOCK_EX);
        });

        //監(jiān)聽WebSocket消息事件
        $this->server->on('message', function (swoole_websocket_server $server, $frame) {
            echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
            //獲取聊天用戶數(shù)組
            $array = explode(',', file_get_contents($this->userFile));
            foreach ($array as $key => $val) {
                $array[$key] = intval($val);
            }
            //組裝消息數(shù)據(jù)
            $msg = json_encode([
                'fd' => $frame->fd,//客戶id
                'msg' => $frame->data,//發(fā)送數(shù)據(jù)
                'total_num' => count($array)//聊天總?cè)藬?shù)
            ], JSON_UNESCAPED_UNICODE);
            //發(fā)送消息
            foreach ($array as $fdId) {
                $server->push($fdId, $msg);
            }
        });

        //監(jiān)聽WebSocket連接關(guān)閉事件
        $this->server->on('close', function ($server, $fd) {
            //獲取聊天用戶數(shù)組
            $array = explode(',', file_get_contents($this->userFile));
            foreach ($array as $key => $val) {
                $array[$key] = intval($val);
            }
            ///組裝消息數(shù)據(jù)
            $msg = json_encode(
                [
                    'fd' => $fd,
                    'msg' => '離開聊天室!',
                    'total_num' => count($array) - 1
                ],
                JSON_UNESCAPED_UNICODE);
            //發(fā)送消息
            foreach ($array as $key => $fdId) {
                if ($fdId == $fd) {
                    unset($array[$key]);
                } else {
                    $server->push($fdId, $msg);
                }
            }
            //更新聊天用戶數(shù)組
            file_put_contents($this->userFile, join(',', $array), LOCK_EX);
            echo "client {$fd} closed\n";
        });

        //監(jiān)聽Http請求事件
        $this->server->on('request', function ($request, $response) {
            // 接收http請求從get獲取message參數(shù)的值,給用戶推送
            // $this->server->connections 遍歷所有websocket連接用戶的fd,給所有用戶推送
            foreach ($this->server->connections as $fd) {
                $this->server->push($fd, $request->get['message']);
            }
        });
        $this->server->start();
    }
}

new Websocket();

使用方法

安裝完php 和swoole擴(kuò)展之后,直接執(zhí)行:

php websocket.php

并可以觀察下輸出,看看websocket服務(wù)器是否正常。
用PHP+swoole做簡單的聊天室


效果如下:

用PHP+swoole做簡單的聊天室


開發(fā)遇到的問題

1代碼中不要用,exit()/die(),socket會(huì)報(bào)   ERROR   zm_deactivate_swoole (ERROR 9003): worker process is terminated by exit()/die(),因?yàn)樽舆M(jìn)程沒有處理就退出了,主進(jìn)程又會(huì)重新拉起。這樣就造成死循環(huán)了。
2.進(jìn)程隔離也是很多新手經(jīng)常遇到的問題。修改了全局變量的值,為什么不生效,原因就是全局變量在不同的進(jìn)程,內(nèi)存空間是隔離的,所以無效。
3.因?yàn)槲业拇a都是在虛擬機(jī)上跑,想讓其他PC訪問,需要做NAT端口映射。

用PHP+swoole做簡單的聊天室
其中,192.168.1.119是我本地ip,192.168.33.10是我虛擬機(jī)的ip,socket服務(wù)是在虛擬機(jī)的9520端口跑的,最后前端代碼的socket端口也相應(yīng)改下就可以了。


前后端代碼在我的git有,有興趣的同學(xué)自行下載~

git地址:https://github.com/onebig32/swoole
歡迎star!


參考:
https://segmentfault.com/a/1190000003057118
NAT端口映射:http://blog.csdn.net/hitabc141592/article/details/31778923
swoole手冊:https://wiki.swoole.com/wiki/page/397.html

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI