安裝swoole官方demo代碼搭建一個websocket,
服務端代碼:ws_server.php
//建立websocket伺服器對象,監聽0.0.0.0:9502連接埠$ws = new swoole_websocket_server("0.0.0.0", 9502);//監聽WebSocket串連開啟事件$ws->on('open', function ($ws, $request) { var_dump($request->fd, $request->get, $request->server); $ws->push($request->fd, "hello, welcome\n");});//監聽WebSocket訊息事件$ws->on('message', function ($ws, $frame) { echo "Message: {$frame->data}\n"; $ws->push($frame->fd, "server: {$frame->data}");});//監聽WebSocket串連關閉事件$ws->on('close', function ($ws, $fd) { echo "client-{$fd} is closed\n";});$ws->start();
用戶端代碼:index.html
我用命令開啟ws_server.php服務端,用戶端檔案index.html放在apache的web根目錄下,我訪問localhost,在console控制台能看到“Connected to WebSocket server.”等訊息,證明訪問成功
但是如果我把ws_server.php的監聽ip改成其他(比如192.168.0.233:9502),然後在index.html相關代碼改成wsServer = 'ws://192.168.0.233:9502';
訪問為什麼就不成功了呢?
回複內容:
安裝swoole官方demo代碼搭建一個websocket,
服務端代碼:ws_server.php
//建立websocket伺服器對象,監聽0.0.0.0:9502連接埠$ws = new swoole_websocket_server("0.0.0.0", 9502);//監聽WebSocket串連開啟事件$ws->on('open', function ($ws, $request) { var_dump($request->fd, $request->get, $request->server); $ws->push($request->fd, "hello, welcome\n");});//監聽WebSocket訊息事件$ws->on('message', function ($ws, $frame) { echo "Message: {$frame->data}\n"; $ws->push($frame->fd, "server: {$frame->data}");});//監聽WebSocket串連關閉事件$ws->on('close', function ($ws, $fd) { echo "client-{$fd} is closed\n";});$ws->start();
用戶端代碼:index.html
我用命令開啟ws_server.php服務端,用戶端檔案index.html放在apache的web根目錄下,我訪問localhost,在console控制台能看到“Connected to WebSocket server.”等訊息,證明訪問成功
但是如果我把ws_server.php的監聽ip改成其他(比如192.168.0.233:9502),然後在index.html相關代碼改成wsServer = 'ws://192.168.0.233:9502';
訪問為什麼就不成功了呢?
設定成0.0.0.0
代表監聽所有地址來源的串連,所以可以進行串連。
而設定成192.168.0.233
表示接受來自192.168.0.233
這個主機的串連,你的本地主機不是192.168.0.233
,串連自然不能建立。