​语音聊天程序源码——简单的聊天室搭建

安装好swoole后开始搭建

前段

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
</head>
<style>
    #set_name{
        margin: auto;
        text-align: center;
    }
</style>
<body>
<h3 style="text-align: center">亮亮的聊天室</h3>
<div id="set_name">
姓名:<input name="name" id="name"><input type="button" onclick="set_name();" value="进入群聊">
</div>
<div id="chat" style="width: 600px; border: red 1px solid;margin: auto;display: none">
    <div id="sayContent" style="height: 300px;border-bottom: silver 1px dashed;">

    </div>
    <div style="height: 75px;margin-top: 10px">
        <textarea id="content" style="height: 50px;width: 480px;background-color: #00a0e9;float: left;"></textarea>
        <button id="submit" style="float: right;height: 55px;width:50px;margin-right:45px;display: block;" onclick="send_msg();">发送</button>
    </div>
</div>
<script>
    var name = ws = '' ;
    //执行websock
    function chat() {
        var wsserver = 'ws://47.94.11.195:443';
        //调用WebSocket对象建立连接
        //ws  wss: // ip:port(字符串)
        ws = new WebSocket(wsserver);
        //获取聊天内容展示窗口
        var sayContent = document.getElementById('sayContent');
        //onopen监听连接打开
        ws.onopen = function (v) {
            var user = new Object();
            user.name = name;
            user.type = 1;//对用户设置姓名
            var json = JSON.stringify(user);
            ws.send(json);//发送数据
        }
        //onmessage监听服务器数据推送
        ws.onmessage = function (v) {
            var html = sayContent.innerHTML;
            sayContent.innerHTML = html + "<br>"+v.data;
        }
        //监听连接关闭
        ws.onclose = function (v) {
            var html = sayContent.innerHTML;
            sayContent.innerHTML = html + "<br>聊天室已关闭!";
        }
    }
    //设置用户名
    function set_name() {
        name = document.getElementById('name').value;
        if(name == ''){
            alert('请输入用户名!');
            return false;
        }
        document.getElementById('set_name').style.display='none';
        document.getElementById('chat').style.display='block';
        chat();
    }
    function send_msg() {
        var content = document.getElementById('content');
        if(content.value == ''){
            alert('请输入聊天内容!');
            return false;
        }

        var msg = new Object();
        msg.content = content.value;
        msg.type = 2;
        var str = JSON.stringify(msg);
        ws.send(str);
    }
</script>
</body>
</html>

后台

<?php
$server = new swoole_websocket_server("0.0.0.0", 443);
$server->users = [];
$server->on('open', function (swoole_websocket_server $server, $request) {
    $server->users[$request->fd]['id'] = $request->fd;
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
    $data = json_decode($frame->data,true);
    if($data['type'] == 1){
        $server->users[$frame->fd]['name']=$data['name'];
        $server->push($frame->fd,'欢迎您('.$data['name'].')进入聊天室!');
    }else{
        foreach($server->users as $v){
            $server->push($v['id'], $server->users[$frame->fd]['name'].'说:'.$data['content']);
        }
    }
});
$server->on('close', function ($ser, $fd) {
    file_put_contents('qq.txt',$server->users[$frame->fd],FILE_APPEND);
    unset($server->users[$frame->fd]);
});
$server->start();
<?php
# 定义 clientFds 数组 保存所有 websocket 连接
$clientFds = [];

# 创建 websocket 服务
$server = new swoole_websocket_server("0.0.0.0", 8080);
# 握手成功 触发回调函数
$server->on('open', function (swoole_websocket_server $server, $request) use (&$clientFds) {
   # echo "server: handshake success with fd{$request->fd}\n";
   # 将所有客户端连接标识,握手成功后保存到数组中
   $clientFds[] = $request->fd;
});
# 收到消息 触发回调函数
$server->on('message', function (swoole_websocket_server $server, $frame) use (&$clientFds) {
   # echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
   # $server->push($frame->fd, "this is server");
   # 当有用户发送信息,发送广播通知所有用户
   foreach ($clientFds as $fd) {
      $server->push($fd, $frame->data);
   }
});
# 关闭连接 触发回调函数
$server->on('close', function ($ser, $fd) use (&$clientFds) {
   # echo "client {$fd} closed\n";
   # 关闭会话 销毁标识 fd
   # 根据 value 去数组中找对应的 key
   $res = array_search($fd, $clientFds, true);
   unset($clientFds[$res]);
});
# 启动 websocket 服务
$server->start();
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>WebSocket 聊天室</title>
</head>
<body>
<div id="main" style="width:600px;height: 200px; overflow: auto;border: solid 2px black;">
</div>
<textarea id="textarea"></textarea>
<br/>
<input type="button" value="发送数据" onclick="send()">
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    var name =prompt("请输入您的昵称","匿名者"); //弹出 input 框
    // 打开一个 web socket
    var ws = new WebSocket("ws://ip:8080");

    ws.onopen = function() {
        console.log("连接成功");
    };

    //收到消息 触发回调
    ws.onmessage = function (evt) {
        var data = evt.data;
        console.log("收到 socket 服务消息,内容:" + data);
        $('#main').append("<p>" + data + "</p>");
    };

    function send() {
        var data = document.getElementById('textarea').value;
        ws.send(name+ ":"+ data);
    }

    ws.onclose = function() {
        // 关闭 websocket
        console.log("连接已关闭...");
    };
</script>
</body>
</html>

原文链接:https://blog.csdn.net/pariese/article/details/79318100

编辑于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券