这篇文章将为大家详细讲解有关workerman实现简单弹幕的示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
弹幕[dàn mù] (barrage),中文流行词语,指的是在网络上观看视频时弹出的评论性字幕。使用workerman实现简单弹幕的方法
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>
<h2>Simple Chat</h2>
<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实现简单弹幕的示例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。