我用swoole搭建一個websocket服務,關於訪問IP的一點疑問

來源:互聯網
上載者:User
關鍵字 php swoole websocket
安裝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,串連自然不能建立。

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.