Heim >Backend-Entwicklung >PHP-Tutorial >我用swoole搭建一个websocket服务,关于访问IP的一点疑问
安装swoole官方demo代码搭建一个websocket,
服务端代码:ws_server.php
<code>//创建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();</code>
客户端代码:index.html
<code><script> var wsServer = 'ws://127.0.0.1:9502'; var websocket = new WebSocket(wsServer); websocket.onopen = function (evt) { console.log("Connected to WebSocket server."); }; websocket.onclose = function (evt) { console.log("Disconnected"); }; websocket.onmessage = function (evt) { console.log('Retrieved data from server: ' + evt.data); }; websocket.onerror = function (evt, e) { console.log('Error occured: ' + evt.data); }; </script></code>
我用命令开启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
<code>//创建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();</code>
客户端代码:index.html
<code><script> var wsServer = 'ws://127.0.0.1:9502'; var websocket = new WebSocket(wsServer); websocket.onopen = function (evt) { console.log("Connected to WebSocket server."); }; websocket.onclose = function (evt) { console.log("Disconnected"); }; websocket.onmessage = function (evt) { console.log('Retrieved data from server: ' + evt.data); }; websocket.onerror = function (evt, e) { console.log('Error occured: ' + evt.data); }; </script></code>
我用命令开启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
,连接自然不能建立。