thinkPhp5 (fastAdmin)框架下workerman 简易通讯demo测试

一、先上效果图

thinkPhp5 (fastAdmin)框架下workerman 简易通讯demo测试

 

二、HTML部分代码

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>socket test case</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 新 Bootstrap 核心 CSS 文件 -->
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var ws = null;
var user = "";
function getWebSocket(){
if ("WebSocket" in window)
{
// 打开一个 web socket
if(!ws){
ws = new WebSocket("ws://SERVER_NAME:2876");
}
return ws;
} else{
// 浏览器不支持 WebSocket
alert("您的浏览器不支持 WebSocket!");
return null;
}
}
ws = getWebSocket();

//连接打开时调用
ws.onopen = function()
{
var timestamp2 = (new Date()).valueOf();
//user = prompt("请输入名字","用户:"+timestamp2);
user = "用户"+timestamp2;
var data = {
"option":"setName",
"name":user,
};
var dataSrt = JSON.stringify(data);
ws.send(dataSrt);
getOnline();
};

ws.onmessage = function (evt)
{
var received_msg = evt.data;
received_msg = JSON.parse(received_msg);
switch(received_msg.option){
case 'setName':
var html = "<div class='row'>"+received_msg.msg+getNowFormatDate()+"<div>";
$("#msgData").prepend(html);
break;
case 'getOnline':
var html = "<option value=''>无</option>";
for(var i=0;i<received_msg.users.length;i++){
if(received_msg.users[i].nickname == user){
html += "<option value='"+received_msg.users[i].keyId+"' style='"+received_msg.users[i].nickname+"</option>";
}else{
html += "<option value='"+received_msg.users[i].keyId+"'>"+received_msg.users[i].nickname+"</option>";
}
}
$("#users").html(html);
break;
case 'outLine':
var html = "<div class='row'>"+received_msg.msg+getNowFormatDate()+"<div>";
$("#msgData").prepend(html);
getOnline();
break;
case 'onLine':
var html = "<div class='row'>"+received_msg.msg+getNowFormatDate()+"<div>";
$("#msgData").prepend(html);
getOnline();
break;
case 'getMsg':
var html = "<div class='row'>"+received_msg.msg+getNowFormatDate()+"<div>";
$("#msgData").prepend(html);
break;
default:
break;
}
};

ws.onclose = function()
{
// 如果连接关闭重新连接
ws = getWebSocket();
};

function getOnline(){
var data = {
"option":"getOnline",
};
var dataSrt = JSON.stringify(data);
ws.send(dataSrt);
}
$(function(){
//获取在线用户
$(".sendMsg").click(function(){
var user = $("#users").val();
var userName = $("#users").find("option:selected").text();
var msgContent = $(".msgContent").val();
if(!user){
console.log("未找到对象.");
return;
}
if(!msgContent){
console.log("不支持输入为空.");
return;
}
var data={
"option":"sendMsg",
"toUser":user,
"msgContent":msgContent,
};
var dataSrt = JSON.stringify(data);
ws.send(dataSrt);

var html = "<div class='row'>给"+userName+"发送消息:"+msgContent+getNowFormatDate()+"<div>";
$("#msgData").prepend(html);
$(".msgContent").val("");
});
});

Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"H+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
};

function getNowFormatDate() {
var thisTime = new Date().Format("yyyy-MM-dd HH:mm:ss");
return "<br>"+thisTime;
}
</script>

<style>
#msgData .row {
margin-right: -15px;
margin-left: -15px;
margin-bottom: 10px;
border-bottom: 1px dashed;
}
</style>
</head>
<body style="padding: 50px;">
<div>
<select id="users" class="form-control">

</select>
</div>
<div style="margin-top: 20px;">
<textarea class="form-control msgContent"></textarea>
</div>
<div class="btn-group" style="margin-top: 20px;margin-bottom: 80px;">
<button type="button" class="btn btn-default sendMsg">提交</button>
</div>
<div id="msgData" style="padding:30px;font-weight:bold;">rgba(99, 193, 244, 0.2);min-height: 35%;">

</div>
</body>
</html>

三、php后台代码Worker
<?php
namespace app\worker\controller;
use Workerman\Lib\Server;
use Workerman\Lib\Timer;

class Worker extends Server
{
protected $socket = 'websocket://0.0.0.0:2876';

public $connectionArr = array();

/**
* 收到信息
* @param $connection
* @param $data
*/
public function onMessage($connection, $data)
{
//{"event": "sendData", "data": "[1,2,,3,4,5]"}
$wsData = json_decode($data,true);
if(!isset($wsData['option'])){
$connection->send('接收数据:'.$data);
return;
}
switch($wsData['option']){
case "setName"://如果是接收数据
$this->setName($connection,$wsData['name']);
break;
case "getOnline"://如果是接收数据
$this->getOnline($connection);
break;
case "sendMsg"://如果是接收数据
$this->sendMsg($connection,$wsData);
break;
default:
$connection->send('其他数据');
break;
}
}

//如果是发送消息
public function sendMsg($connection,$data){
$msgStr = json_encode(array("option"=>"getMsg","msg"=>"来自".$connection->nickname."的消息:".$data['msgContent']));
$this->connectionArr[$data['toUser']]->send($msgStr);
}

//获取在线用户
public function getOnline($connection){
$users = array();
foreach($this->connectionArr as $keyId=>$conn){
$users[] = array("keyId"=>$keyId,"nickname"=>$conn->nickname);
}
$msgStr = json_encode(array("option"=>"getOnline","users"=>$users));
$connection->send($msgStr);
}

//设置姓名
public function setName($connection,$uName){
$connection->nickname = $uName;

//通知其他用户有用户上线了..
foreach($this->connectionArr as $keyId=>$conn){
$msgStr = json_encode(array("option"=>"onLine","msg"=>$conn->nickname." 进入了频道..."));
$conn->send($msgStr);
}
$this->connectionArr[$connection->keyId] = $connection;
$msgStr = json_encode(array("option"=>"setName","msg"=>"当前用户名称设置为:".$uName));
$connection->send($msgStr);
}

/**
* 当连接建立时触发的回调函数
* @param $connection
*/
public function onConnect($connection)
{
//给新连接进来的socket一个唯一的ID
$keyId = uniqid().mt_rand(10000,99999);
$connection->keyId = $keyId;
$connection->nickname = "游客";
$this->connectionArr[$keyId] = $connection;
}

/**
* 当连接断开销毁连接对象节约内存空间
* @param $connection
*/
public function onClose($connection)
{
unset($this->connectionArr[$connection->keyId]);

//通知其他人用户离线了
foreach($this->connectionArr as $keyId=>$conn){
$msgStr = json_encode(array("option"=>"outLine","msg"=>$conn->nickname." 离开了频道..."));
$conn->send($msgStr);
}
unset($connection);
}

/**
* 当客户端的连接上发生错误时触发
* @param $connection
* @param $code
* @param $msg
*/
public function one rror($connection, $code, $msg)
{
echo "\r\n error $code $msg\n";
}

/**
* 每个进程启动
* @param $worker
*/
public function onWorkerStart($worker)
{
echo "\r\n process start";
}

// 当连接断开时触发的回调函数 终止timer事件
// public function onClose($connection)
// {
// Timer::del($connection->timer_id);
// echo "\r\n process close $connection->timer_id";
// }
// Timer事件
// public function eventGetData($connection){
// $time_interval = 1;
// $connection->timer_id = Timer::add($time_interval,function()use($connection)
// {
// $id = $connection->lastId;
// $sql = "SELECT * FROM ccgisdata WHERE id > {$id} ORDER BY id";
// $dataStr = pdo_fetch($sql);
// $connection->lastId = $dataStr['id'];
// $connection->send($dataStr['data']);
// });
// }
}
上一篇:thinkphp5实现文章上一篇,下一篇


下一篇:thinkphp5在Linux下Nginx配置问题解决