Linux下源码包安装Swoole及基本使用操作图文详解(3)

启动服务:

php http_server.php

(如果9501端口已经被占用查看进程PID,杀死进程:)

lsof -i:9501

kill 9013

浏览器访问主机地址:端口号,得到程序预期结果即测试成功:


【创建WebSocket服务器】

创建ws_server.php:

<?php
  //创建websocket服务器对象,监听0.0.0.0:9501端口
  $ws = new swoole_websocket_server("0.0.0.0", 9501);
  
  //配置静态文件根目录(可选)
  $ws ->set([
    'document_root' => '/www/wwwroot/lwsblog',
    'enable_static_handler' => true,
  ]);

  //监听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();

运行程序:(这里还是要确认监听的端口没有被占用,如果被占用查看进程PID,杀死进程)

php ws_server.php

前端页面js监听:(127.0.0.1改成你的主机地址)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>WebSocket</title>
</head>
<body>
</body>

<script type="text/javascript">
var wsServer = 'ws://127.0.0.1:9501';
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>
</html>

使用谷歌浏览器访问前端页面:

服务器端收到请求信息: