首先下載workerman??https://www.workerman.net/download? ? ? ? (推薦學(xué)習(xí): workerman教程)
下載好后在workerman文件下創(chuàng)建一個(gè)新的文件start.php?
代碼如下
<?php use WorkermanWorker; //Autoloader.php路徑 require_once "./Autoloader.php"; $global_uid = 0; // 當(dāng)客戶端連上來(lái)時(shí)分配uid,并保存連接,并通知所有客戶端 function handle_connection($connection) { global $text_worker, $global_uid; // 為這個(gè)連接分配一個(gè)uid $connection->uid?=?++$global_uid; } ? //?當(dāng)客戶端發(fā)送消息過(guò)來(lái)時(shí),轉(zhuǎn)發(fā)給所有人 function?handle_message($connection,?$data) { ????global?$text_worker; ????foreach($text_worker->connections?as?$conn) ????{ ????????$conn->send("user[{$connection->uid}]?said:?$data"); ????} } ? //?當(dāng)客戶端斷開(kāi)時(shí),廣播給所有客戶端 function?handle_close($connection) { ????global?$text_worker; ????foreach($text_worker->connections?as?$conn) ????{ ????????$conn->send("user[{$connection->uid}]?logout"); ????} } ? //?創(chuàng)建一個(gè)文本協(xié)議的Worker監(jiān)聽(tīng)2000接口??用0.0.0.0方便鏈接內(nèi)網(wǎng)外網(wǎng) $text_worker?=?new?Worker("websocket://0.0.0.0:2000");?? ? //?只啟動(dòng)1個(gè)進(jìn)程,這樣方便客戶端之間傳輸數(shù)據(jù) $text_worker->count?=?1; ? $text_worker->onConnect?=?'handle_connection'; $text_worker->onMessage?=?'handle_message'; $text_worker->onClose?=?'handle_close'; ? Worker::runAll();
然后命令行運(yùn)行? ?php start.php start
簡(jiǎn)單測(cè)打開(kāi)瀏覽器,按F12打開(kāi)調(diào)試控制臺(tái),在console一欄輸入(或者把下面代碼放入到html頁(yè)面用JS運(yùn)行
//?假設(shè)服務(wù)端ip為127.0.0.1 ws?=?new?WebSocket("ws://127.0.0.1:2000"); ws.onopen?=?function()?{ ????alert("連接成功"); ????ws.send('我是誰(shuí)?'); ????alert("給服務(wù)端發(fā)送一個(gè)字符串:我是誰(shuí)?"); }; ws.onmessage?=?function(e)?{ ????alert("收到服務(wù)端的消息:"?+?e.data); };
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END