弹幕[dàn mù] (barrage),中文流行词语,指的是在网络上观看视频时弹出的评论性字幕。下面我们就来看一下使用workerman实现简单弹幕的方法。

怎么从一名码农成为架构师的必看知识点:目录大全(持续更新)50w年薪挑战!

php代码:

<?php  

use workerman\worker;  

require_once '../autoloader.php';//注意 这里要看你的workerman里的这个文件在哪 然后在进行修改  

   

$global_uid = 0;  

   

// 当客户端连上来时分配uid,并保存连接,并通知所有客户端  

function handle_connection($connection) {  

    global $text_worker, $global_uid;  

    // 为这个链接分配一个uid  

    $connection->uid = ++$global_uid;  

    foreach ($text_worker->connections as $conn) {  

        $conn->send("user[{$connection->uid}] online");  

    }  

}  

   

// 当客户端发送消息过来时,转发给所有人  

function handle_message($connection, $data) {  

    global $text_worker;  

    foreach ($text_worker->connections as $conn) {  

        $conn->send("user[{$connection->uid}] said: $data");  

    }  

}  

   

// 当客户端断开时,广播给所有客户端  

function handle_close($connection) {  

    global $text_worker;  

    foreach ($text_worker->connections as $conn) {  

        $conn->send("user[{$connection->uid}] logout");  

    }  

}  

   

$text_worker = new worker("websocket://0.0.0.0:2347");  

   

$text_worker->count = 1;  

   

$text_worker->onconnect = 'handle_connection';  

$text_worker->onmessage = 'handle_message';  

$text_worker->onclose = 'handle_close';  

   

worker::runall();

  

 

html代码:

<!doctype html>  

 

<html>  

<head>  

    <meta charset="utf-8">  

    <title>simple chat</title>  

</head>  

<body>  

    <center> 

<h1>simple chat</h1>  

<input type="text" id="msg">  

<button type="button" id="send">send</button> 

 

 

<div id="content" style="width:200px;height:200px;border:1px solid red">

    假装在播放视频

    <marquee behavior="" direction=""></marquee>

</div>  

</center>

</body>  

   

<script type="text/javascript">  

    window.onload = function () {  

        var ws = new websocket("ws://127.0.0.1:2347");  

   

        document.getelementbyid("send").onclick = function () {  

            var msg = document.getelementbyid("msg").value;  

            ws.send(msg);  

        };  

   

        ws.onopen = function () {  

            console.log("连接成功");  

//            ws.send('raid');  

        };  

        ws.onmessage = function (e) {  

            document.getelementbyid("content").innerhtml += '<marquee behavior="" direction="">' + e.data + '</marquee>';  

        };  

    };  

</script>  

   

</html>

  

以上就是workerman实现简单弹幕的方法的详细内容

更多内容请访问

怎么从一名码农成为架构师的必看知识点:目录大全(持续更新)50w年薪挑战!