swoole用WebSocket服务器搭建一个简易的聊天室功能

Posted wgchen~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swoole用WebSocket服务器搭建一个简易的聊天室功能相关的知识,希望对你有一定的参考价值。

域名无ssl加密

WS.php写服务端代码

<?php
class WS{
    private $ws = null;
    
    public function __construct(){
        //创建WebSocket Server对象,监听0.0.0.0:9502端口
        $this->ws = new Swoole\\WebSocket\\Server('0.0.0.0', 9502);
        //监听WebSocket连接打开事件
        $this->ws->on('Open', [$this, "onOpen"]);
        //监听WebSocket消息事件
        $this->ws->on('Message', [$this, "onMessage"]);
        //监听WebSocket连接关闭事件
       $this->ws->on('Close', [$this, "onClose"]);
        //启动服务器
       $this->ws->start();
    }
    public function onOpen($ws, $request){
        var_dump($request->fd, $request->get, $request->server);
        $ws->push($request->fd, "欢迎客户端: {$request->fd}\\n");
    }
    public function onMessage($ws, $frame){
        echo "信息: {$frame->data}\\n";
        foreach($ws->connections as $fd){
            //$fd指单前用户,$frame->fd外来连接的用户
            if($fd == $frame->fd){
                $ws->push($fd, "我: {$frame->data}");
            }else{
                $ws->push($fd, "对方: {$frame->data}");
            }
        }
    }
    public function onClose($ws, $fd){
        echo "客服端:{$fd} 关闭\\n";
    }
}
new WS();

chat.html写客户端代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>简易聊天室</title>
</head>
<div id="welcome"></div>
<input type="text" id="input"/>
<input type="buton" onclick="send()" value="发送"/>
<div id="message"></div>
<body>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
    var wsServer = 'ws://xiangyu.huangzhongxin.cn:9502';
    var websocket = new WebSocket(wsServer);
    websocket.onopen = function (res) {
        $("#welcome").append("<h1>连接成功!欢迎</h1>");
    };
    websocket.onclose = function (res) {
        $("#message").append("<h3>连接关闭</h3>");
    };
    websocket.onmessage = function (res) {
        $("#message").append("<h3>" + res.data + "</h3>");
    };
    websocket.onerror = function (res) {
        $("#message").append("<h3>" + res + "</h3>");
    };
    function send(){
        websocket.send($('#input').val());
    }
</script>
</html>

域名有ssl加密

WS.php写服务端代码

<?php
class WS{
    private $ws = null;
    
    public function __construct(){
        //创建WebSocket Server对象,监听0.0.0.0:9502端口
        $this->ws = new Swoole\\WebSocket\\Server('0.0.0.0', 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);
        
        //配置ssl文件路径,记得修改为自己ssl的路径
        $this->ws->set([
            'ssl_cert_file' => '/www/server/panel/vhost/cert/xxxxx/fullchain.pem',
            'ssl_key_file' => '/www/server/panel/vhost/cert/xxxxx/privkey.pem',
        ]);
        
        //监听WebSocket连接打开事件
        $this->ws->on('Open', [$this, "onOpen"]);
        
        //监听WebSocket消息事件
        $this->ws->on('Message', [$this, "onMessage"]);
        
        //监听WebSocket连接关闭事件
       $this->ws->on('Close', [$this, "onClose"]);
        
        //启动服务器
       $this->ws->start();
    }
    
    public function onOpen($ws, $request){
        var_dump($request->fd, $request->get, $request->server);
        $ws->push($request->fd, "欢迎客户端: {$request->fd}\\n");
    }
    
    public function onMessage($ws, $frame){
        echo "信息: {$frame->data}\\n";
        foreach($ws->connections as $fd){
            //$fd指单前用户,$frame->fd外来连接的用户
            if($fd == $frame->fd){
                $ws->push($fd, "我: {$frame->data}");
            }else{
                $ws->push($fd, "对方: {$frame->data}");
            }
        }
        
    }
    
    public function onClose($ws, $fd){
        echo "客服端:{$fd} 关闭\\n";
    }
}
new WS();

chat.html写客户端代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>简易聊天室</title>
</head>
<div id="welcome"></div>
<input type="text" id="input"/>
<input type="buton" onclick="send()" value="发送"/>
<div id="message"></div>
<body>
</body>

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
    var wsServer = 'wss://xiangyu.huangzhongxin.cn:9502';
    var websocket = new WebSocket(wsServer);
    websocket.onopen = function (res) {
        $("#welcome").append("<h1>连接成功!欢迎</h1>");
    };
    
    websocket.onclose = function (res) {
        $("#message").append("<h3>连接关闭</h3>");
    };
    
    websocket.onmessage = function (res) {
        $("#message").append("<h3>" + res.data + "</h3>");
    };
    
    websocket.onerror = function (res) {
        $("#message").append("<h3>" + res + "</h3>");
    };
    
    function send(){
        websocket.send($('#input').val());
    }
</script>
</html>


开启服务端常链接

php WS.php

注:如果开启不了可能是9502端口被占用了,杀死即可

netstat -anp  | grep  9501  	//查看端口号 9501

浏览器分别开启两个客户端窗口,进行聊天


以上是关于swoole用WebSocket服务器搭建一个简易的聊天室功能的主要内容,如果未能解决你的问题,请参考以下文章

基于 Swoole 搭建 WebSocket 服务详解

Laravel + Swoole 打造IM简易聊天室

Laravel + Swoole 打造IM简易聊天室

swoole webSocket 聊天室示例

swoole 安装 搭建tcp服务器和websocket

Laravel + Swoole 打造IM简易聊天室