彈幕[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年薪挑戰!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/75623.html
標籤:PHP
下一篇:OSX下安裝PHP7教程詳解
