我想用PHP來實現的WebSocket並作爲擴展警予,這樣我可以爲我的web應用程序phpwebsockets警予執行
從下面鏈接的代碼創建一個類似功能的通知就是我的出發點:
http://www.flynsarmy.com/2012/02/php-websocket-chat-application-2-0/
它完全在我的本地XAMPP ..
我試着將它作爲一個Yii的擴展的步驟,我也跟着..
- 我已經把在YII擴展文件夾類PHPWebSocket.php ..
- 我創建了一個控制器的WebSocket和動作的startserver和動作指數(對於聊天界面來測試從上面的鏈接的例子)
這裏是代碼片段
<?php
Yii::import("ext.websocket.PHPWebSocket");
class WebSocketController extends Controller {
public $layout = '//layouts/empty';
public function actionStartServer() {
set_time_limit(0);
function wsOnMessage($clientID, $message, $messageLength, $binary) {
global $Server;
$ip = long2ip($Server->wsClients[$clientID][6]);
// check if message length is 0
if ($messageLength == 0) {
$Server->wsClose($clientID);
return;
}
//The speaker is the only person in the room. Don't let them feel lonely.
if (sizeof($Server->wsClients) == 1)
$Server->wsSend($clientID, "There isn't anyone else in the room, but I'll still listen to you. --Your Trusty Server");
else
//Send the message to everyone but the person who said it
foreach ($Server->wsClients as $id => $client)
if ($id != $clientID)
$Server->wsSend($id, "Visitor $clientID ($ip) said \"$message\"");
}
// when a client connects
function wsOnOpen($clientID) {
global $Server;
$ip = long2ip($Server->wsClients[$clientID][6]);
$Server->log("$ip ($clientID) has connected.");
//Send a join notice to everyone but the person who joined
foreach ($Server->wsClients as $id => $client)
if ($id != $clientID)
$Server->wsSend($id, "Visitor $clientID ($ip) has joined the room.");
}
// when a client closes or lost connection
function wsOnClose($clientID, $status) {
global $Server;
$ip = long2ip($Server->wsClients[$clientID][6]);
$Server->log("$ip ($clientID) has disconnected.");
//Send a user left notice to everyone in the room
foreach ($Server->wsClients as $id => $client)
$Server->wsSend($id, "Visitor $clientID ($ip) has left the room.");
}
$Server = new PHPWebSocket();
$Server->bind('message', 'wsOnMessage');
$Server->bind('open', 'wsOnOpen');
$Server->bind('close', 'wsOnClose');
$Server->wsStartServer('127.0.0.1', 9300);
}
public function actionIndex() {
$this->render('index');
}
}
是我的方式來使用PHP是正確的或者是不可能這樣做創建的WebSocket ..
我只想實現相同的使用PHP,因爲我更喜歡使用node.js或任何其他腳本
您可以運行命令行應用程序嗎?如果是這樣,以這種方式運行你的服務器可能會讓你的服務器更長時間... – acorncom
你無法從控制器內的客戶端請求啓動websocket服務器。您應該從命令行運行服務器並繼續運行。 – Stan
嗨@fuzionpro我看到了這個關於websocket和php的教程,我想在yii中實現它。你有沒有找到一個解決方案如何將這與yii集成。謝謝 – HADEV