swoole+websocket聊天室简易版(前后端代码)

php代码

<?php

class WS
{
    private $server = null;

    public function __construct()
    {
        $this->server = new Swoole\WebSocket\Server('0.0.0.0', 9502);//让有ssl证书的也可以运行
//        $this->server = new Swoole\WebSocket\Server('0.0.0.0', 9502, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);//让有ssl证书的也可以运行
//        $this->server->set([
//            'ssl_cert_file' => '证书目录',
//            'ssl_key_file' => '目录'
//        ]);
        $this->server->on('Open', [$this, 'open']);
        $this->server->on('Message', [$this, 'message']);
        $this->server->on('Close', [$this, 'close']);
        $this->server->start();
    }

    public function open($ws, $request)
    {
        $ws->push($request->fd, "hello, welcome\n");
    }

    public function message($ws, $frame)
    {
        echo "Message: {$frame->data}\n";
        foreach ($ws->connections  as $fd) {
            if ($fd == $frame->fd) {
                $ws->push($fd, "我:{$frame->data}");
            } else {
                $ws->push($fd, "对方:{$frame->data}");
            }
        }
    }

    public function close($ws, $fd)
    {
        echo "client-{$fd} is closed\n";
    }

}

new WS();

  • 使用php swoole

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input id="val" type="text">
<input onclick="fasong()" type="button" value="点击">

</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
<script>
    var ws = new WebSocket('ws://localhost:9502');
    function open(){
        console.log('open');
    }
    function message(e){
        console.log("收到消息了:",e)
    }
    function close(){
        console.log('关闭')

    }
    function error(){
        console.log('error');

    }
    ws.onopen =open;
    ws.onmessage=message;
    ws.onclose=close;
    ws.onerror=error;
    function fasong(){
        let val = $('#val').val();
        console.log(val);
        ws.send(val);
        $('#val').val('');
    }

</script>
</html>

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值