一、服务端
<?php
require_once __DIR__ . '/Workerman/Autoloader.php';
use Workerman\Worker;
use Workerman\Lib\Timer;
$worker = new Worker('websocket://0.0.0.0:8383');
$worker->count=1;
$worker->userList=[];
$worker->onMessage=function ($user,$data){
global $worker;
if(!isset($user->uid)){
$user->uid=$user->id; //此处为了方便测试把会话id作为用户id 详情见官方文档
$worker->userList[$user->uid] = $user;
}
$data = '1:hello'; //假设发来的消息是这样的结构
list($uid,$msg)=explode(':',$data);
if(!$uid){ //群发
broadcast($msg);
}else{ //单发
sendMessageByUid($uid, $msg);
}
};
// 群发
function broadcast($message)
{
global $worker;
foreach($worker->uidConnections as $connection)
{
$connection->send($message);
}
}
// 发给一个人
function sendMessageByUid($uid, $message)
{
global $worker;
if(isset($worker->userList[$uid]))
{
$connection = $worker->userList[$uid];
$connection->send($message);
}
}
// 当有客户端连接断开时
$worker->onClose = function($connection)
{
global $worker;
if(isset($connection->uid))
{
// 连接断开时删除映射
unset($worker->userList[$connection->uid]);
}
};
Worker::runAll();
二、客户端
<script>
var ws = new WebSocket("ws://47.98.247.97:8383");
ws.onmessage = function(e){ //接收服务器发来的消息
console.log('接收'+e.data);
};
function send(){
let msg = $('#msg').val();
ws.send(msg);
}
</script>