//创建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
,连接自然不能建立。