服務(wù)器
<?php
use Workerman\Worker;
require_once './Workerman/Autoloader.php';
// 初始化一個(gè)worker容器,監(jiān)聽(tīng)1234端口
$worker = new Worker('websocket://127.0.0.1:1234');
/*
* 注意這里進(jìn)程數(shù)必須設(shè)置為1,否則會(huì)報(bào)端口占用錯(cuò)誤
* (php 7可以設(shè)置進(jìn)程數(shù)大于1,前提是$inner_text_worker->reusePort=true)
*/
$worker->count = 1;
// worker進(jìn)程啟動(dòng)后創(chuàng)建一個(gè)text Worker以便打開(kāi)一個(gè)內(nèi)部通訊端口
$worker->onWorkerStart = function($worker)
{
// 開(kāi)啟一個(gè)內(nèi)部端口,方便內(nèi)部系統(tǒng)推送數(shù)據(jù),Text協(xié)議格式 文本+換行符
$inner_text_worker = new Worker('text://127.0.0.1:5678');
$inner_text_worker->onMessage = function($connection, $buffer)
{
global $worker;
// $data數(shù)組格式,里面有uid,表示向那個(gè)uid的頁(yè)面推送數(shù)據(jù)
$data = json_decode($buffer, true);
$uid = $data;
// 通過(guò)workerman,向uid的頁(yè)面推送數(shù)據(jù)
$ret = sendMessageByUid($uid, $buffer);
// 返回推送結(jié)果
$connection->send($ret ? 'ok' : 'fail');
};
// 執(zhí)行監(jiān)聽(tīng)
$inner_text_worker->listen();
};
// 新增加一個(gè)屬性,用來(lái)保存uid到connection的映射
$worker->uidConnections = array();
// 當(dāng)有客戶端發(fā)來(lái)消息時(shí)執(zhí)行的回調(diào)函數(shù)
$worker->onMessage = function($connection, $data)use($worker)
{
// 判斷當(dāng)前客戶端是否已經(jīng)驗(yàn)證,既是否設(shè)置了uid
if(!isset($connection->uid))
{
// 沒(méi)驗(yàn)證的話把第一個(gè)包當(dāng)做uid(這里為了方便演示,沒(méi)做真正的驗(yàn)證)
$connection->uid = $data;
/* 保存uid到connection的映射,這樣可以方便的通過(guò)uid查找connection,
* 實(shí)現(xiàn)針對(duì)特定uid推送數(shù)據(jù)
*/
$worker->uidConnections = $connection;
return;
}
};
// 當(dāng)有客戶端連接斷開(kāi)時(shí)
$worker->onClose = function($connection)use($worker)
{
global $worker;
if(isset($connection->uid))
{
// 連接斷開(kāi)時(shí)刪除映射
unset($worker->uidConnections);
}
};
// 向所有驗(yàn)證的用戶推送數(shù)據(jù)
function broadcast($message)
{
global $worker;
foreach($worker->uidConnections as $connection)
{
$connection->send($message);
}
}
// 針對(duì)uid推送數(shù)據(jù)
function sendMessageByUid($uid, $message)
{
global $worker;
if(isset($worker->uidConnections))
{
$connection = $worker->uidConnections;
$connection->send($message);
return true;
}
return false;
}
// 運(yùn)行所有的worker
Worker::runAll();
客戶端
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
//ws.send('hello world');
function connect(){
var ws =new WebSocket('ws://127.0.0.1:1234');
ws.onpen=function(){
var uid ='uid1';alert(uid);
ws.send(uid);
};
ws.onmessage=function(e){
alert(e.data);
}
}
</script>
</head>
<body onload="connect();">
<div>TODO write content</div>
</body>
</html>