如何在PHP 中建立WebSocket 伺服器
建立WebSocket 伺服器可能是一項具有挑戰性的任務,特別是當您遇到過時的程式碼或不完整的文檔時。以下是引導您完成整個流程的詳細解決方案:
伺服器端程式碼:
<?php set_time_limit(0); ob_implicit_flush(); $master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($master, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($master, "localhost", 12345); socket_listen($master, 20); $sockets = array($master); $users = array(); while (true) { $changed = $sockets; socket_select($changed, $write=NULL, $except=NULL, NULL); foreach ($changed as $socket) { if ($socket == $master) { $client = socket_accept($master); if ($client < 0) { echo "socket_accept() failed\n"; continue; } else { connect($client); } } else { $bytes = @socket_recv($socket, $buffer, 2048, 0); if ($bytes == 0) { disconnect($socket); } else { $user = getuserbysocket($socket); if (!$user->handshake) { dohandshake($user, $buffer); } else { process($user, $buffer); } } } } } function connect($socket) { global $sockets, $users; $user = new User(); $user->id = uniqid(); $user->socket = $socket; array_push($users, $user); array_push($sockets, $socket); echo $socket." CONNECTED!\n"; } function disconnect($socket) { global $sockets, $users; $found = null; $n=count($users); for ($i=0;$isocket == $socket) { $found = $i; break; } } if (!is_null($found)) { array_splice($users, $found, 1); } $index = array_search($socket, $sockets); socket_close($socket); echo $socket." DISCONNECTED!\n"; if ($index>=0) { array_splice($sockets, $index, 1); } } function dohandshake($user, $buffer) { $headers = getheaders($buffer); $acceptkey = base64_encode(sha1($headers[4] . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true)); $upgrade = "HTTP/1.1 101 Switching Protocols\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "Sec-WebSocket-Accept: $acceptkey\r\n\r\n"; socket_write($user->socket, $upgrade, strlen($upgrade)); $user->handshake = true; echo "Done handshaking...\n"; } function getheaders($req) { $r=$h=$u=$c=$key=$protocol=$version=$o=$data=null; if (preg_match("/GET (.*) HTTP/", $req, $match)) { $r = $match[1]; } if (preg_match("/Host: (.*)\r\n/", $req, $match)) { $h = $match[1]; } if (preg_match("/Upgrade: (.*)\r\n/", $req, $match)) { $u = $match[1]; } if (preg_match("/Connection: (.*)\r\n/", $req, $match)) { $c = $match[1]; } if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $req, $match)) { $key = $match[1]; } if (preg_match("/Sec-WebSocket-Protocol: (.*)\r\n/", $req, $match)) { $protocol = $match[1]; } if (preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $req, $match)) { $version = $match[1]; } if (preg_match("/Origin: (.*)\r\n/", $req, $match)) { $o = $match[1]; } if (preg_match("/\r\n(.*?)$/", $req, $match)) { $data = $match[1]; } return array($r,$h,$u,$c,$key,$protocol,$version,$o,$data); } function getuserbysocket($socket) { global $users; $found = null; foreach ($users as $user) { if ($user->socket == $socket) { $found = $user; break; } } return $found; } class User { var $id; var $socket; var $handshake; } ?>
客戶端代碼:
var connection = new WebSocket('ws://localhost:12345'); connection.onopen = function () { connection.send('Ping'); }; connection.onerror = function (error) { console.log('WebSocket Error ' + error); }; connection.onmessage = function (e) { console.log('Server: ' + e.data); };
故障排除:
如果遇到錯誤訊息「Firefox無法與位於ws:// 的伺服器建立連線” localhost:12345/”,檢查以下內容:
- 確保您的伺服器程式碼正在執行連接埠12345。客戶端程式碼是否連接到正確的主機名稱和連接埠。規格中概述的 WebSocket 握手過程.
- 確保正確處理 WebSocket 幀和屏蔽。
以上是如何用 PHP 建置 WebSocket 伺服器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

stickysessensureuserRequestSarerOutedTothesMeServerForsessionDataConsisterency.1)sessionIdentificeAssificationAssigeaSsignAssignSignSuserServerServerSustersusiseCookiesorUrlModifications.2)一致的ententRoutingDirectSsssssubsequeSssubsequeSubsequestrequestSameSameserver.3)loadBellankingDisteributesNebutesneNewuserEreNevuseRe.3)

phpoffersvarioussessionsionsavehandlers:1)文件:默認,簡單的ButMayBottLeneckonHigh-trafficsites.2)Memcached:高性能,Idealforsforspeed-Criticalapplications.3)REDIS:redis:similartomemememememcached,withddeddeddedpassistence.4)withddeddedpassistence.4)databases:gelifforcontrati forforcontrati,有用

PHP中的session是用於在服務器端保存用戶數據以在多個請求之間保持狀態的機制。具體來說,1)session通過session_start()函數啟動,並通過$_SESSION超級全局數組存儲和讀取數據;2)session數據默認存儲在服務器的臨時文件中,但可通過數據庫或內存存儲優化;3)使用session可以實現用戶登錄狀態跟踪和購物車管理等功能;4)需要注意session的安全傳輸和性能優化,以確保應用的安全性和效率。

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

絕對會話超時從會話創建時開始計時,閒置會話超時則從用戶無操作時開始計時。絕對會話超時適用於需要嚴格控制會話生命週期的場景,如金融應用;閒置會話超時適合希望用戶長時間保持會話活躍的應用,如社交媒體。

服務器會話失效可以通過以下步驟解決:1.檢查服務器配置,確保會話設置正確。 2.驗證客戶端cookies,確認瀏覽器支持並正確發送。 3.檢查會話存儲服務,如Redis,確保其正常運行。 4.審查應用代碼,確保會話邏輯正確。通過這些步驟,可以有效診斷和修復會話問題,提升用戶體驗。

session_start()iscucialinphpformanagingusersessions.1)ItInitiateSanewsessionifnoneexists,2)resumesanexistingsessions,and3)setsasesessionCookieforContinuityActinuityAccontinuityAcconActInityAcconActInityAcconAccRequests,EnablingApplicationsApplicationsLikeUseAppericationLikeUseAthenticationalticationaltication and PersersonalizedContentent。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver CS6
視覺化網頁開發工具

記事本++7.3.1
好用且免費的程式碼編輯器

禪工作室 13.0.1
強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。