这里我们使用php+swoole编写一个简单的静态http服务
构建web服务器
<?php
/**
* Created by PhpStorm.
* User: 2yq
* Date: 2021/9/22
* Time: 15:29
*/
$web = new \Swoole\Http\Server('0.0.0.0',6070);
$web->set([
'worker_num' => 1
]);
$web->on('Request',function ($request,$response){
//设置响应的状态码
$response->status(400);
//设置响应头
$response->header('Content-type','text/html;charset=utf-8');
//请求响应的内容
$response->end('<h1>hello world!'.rand(1000,9000).'</h1>');
});
//启动服务
$web->start();
使用浏览器访问服务器地址结果如图所示:
可以看出这里我就完成了一个简单的web服务器
ab进行压力测试
ab -c1000 -n1000 -k url地址
-c 并发的人数
-n 总的请求人数
-k 保持连接
构建静态服务器
<?php
/**
* Created by PhpStorm.
* User: 2yq
* Date: 2021/9/22
* Time: 15:29
*/
$web = new \Swoole\Http\Server('0.0.0.0',6070);
$web->set([
'worker_num' => 1,
//静态文件目录
'document_root' => '/var/www/html/static', // v4.4.0以下版本, 此处必须为绝对路径
'enable_static_handler' => true,
]);
$web->on('Request',function ($request,$response){
$response->status(400);
$response->header('Content-type','text/html;charset=utf-8');
$response->end('<h1>hello world!你好 世界!'.rand(1000,9000).'</h1>');
});
$web->start();
设置 document_root
并设置 enable_static_handler
为 true
后,底层收到 Http
请求会先判断 document_root 路径下是否存在此文件,如果存在会直接发送文件内容给客户端,不再触发 onRequest 回调。
document_root的目录为你静态文件存放的绝对路径
运行结果
index.html
index2.html
构建动态服务器
动态服务器可以高性能的动态解析php的服务器,这里搭建一个简单的动态服务器
<?php
/**
* Created by PhpStorm.
* User: 快定
* Date: 2021/9/23
* Time: 9:45
*/
$server = new \Swoole\Http\Server('0.0.0.0', 6070);
$server->set([
'worker_num' => 1,
]);
$server->on('Request', function ($request, $response) {
//request中有很多参数,这里之所以需要添加/static是因为我将php文件放在static目录下
$file_path = __DIR__. '/static' . $request->server['request_uri'];
$status = 404;
$html="页面丢了";
if (file_exists($file_path)){
$status = 200;
//运行php文件
include $file_path;
}
$response->status($status);
$response->end($html);
});
$server->start();
$request参数包含参数
object(Swoole\Http\Request)#6 (9) {
["fd"]=>
int(2)
["streamId"]=>
int(0)
["header"]=>
array(8) {
["host"]=>
string(17) "8.131.95.189:6070"
["connection"]=>
string(10) "keep-alive"
["cache-control"]=>
string(9) "max-age=0"
["upgrade-insecure-requests"]=>
string(1) "1"
["user-agent"]=>
string(113) "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.8 Safari/537.36"
["accept"]=>
string(135) "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
["accept-encoding"]=>
string(13) "gzip, deflate"
["accept-language"]=>
string(14) "zh-CN,zh;q=0.9"
}
["server"]=>
array(10) {
["request_method"]=>
string(3) "GET"
["request_uri"]=>
string(8) "/Api.php"
["path_info"]=>
string(8) "/Api.php"
["request_time"]=>
int(1632362111)
["request_time_float"]=>
float(1632362111.8686)
["server_protocol"]=>
string(8) "HTTP/1.1"
["server_port"]=>
int(6070)
["remote_port"]=>
int(56719)
["remote_addr"]=>
从结果中可以看到$request->server[‘request_uri’]为执行的文件的目录
运行结果
api.php代码:
<?php
echo json_encode(['id' => 1, 'name' => 'wyq', 'sex' => '男'],256);
这样我们发现一个问题,代码运行在服务端,运行代码的界面还是无法展示运行的结果,需要解决这个问题,有一个办法就是开启缓存区,将运行的结果先保存在缓存区中,然后返回到运行界面。
具体代码如下:
<?php
/**
* Created by PhpStorm.
* User: 快定
* Date: 2021/9/23
* Time: 9:45
*/
$server = new \Swoole\Http\Server('0.0.0.0', 6070);
$server->set([
'worker_num' => 1,
]);
$server->on('Request', function ($request, $response) {
$file_path = __DIR__ . '/static' . $request->server['request_uri'];
$status = 404;
$html = "页面丢了";
if (file_exists($file_path)) {
$status = 200;
//开启缓存区
ob_start();
//运行php代码
include $file_path;
//获取到缓存区的数据
$html = ob_get_contents();
//清空缓存区
ob_clean();
}
$response->status($status);
//设置返回为json类型
$response->header('Content-type','application/json;charset=utf8');
$response->end($html);
});
$server->start();
运行结果:
这样就完成了一个可以解析php的动态服务器
构建websocket服务器
WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输
websocket解决服务器端与客户端即时通信的问题。
html5中的websocket Api
//ws 为协议名
//localhost 为主机
//6070为端口
var websocket = new WebSocket("ws://localhost:6070");
事件:
事件 | 事件处理程序 | 描述 |
---|---|---|
open | websocket.onopen | 连接时触发 |
message | websocket.message | 客户端接收服务端数据时触发 |
onerror | websocket.onerror | 通信发生错误时触发 |
onclose | websocket.onclose | 连接关闭时触发 |
方法:
方法 | 描述 |
---|---|
send | 使用连接发送数据 |
close | 关闭连接 |
服务端的代码具体实现
<?php
//创建WebSocket Server对象,监听0.0.0.0:6070端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 6070);
//监听WebSocket连接打开事件
$ws->on('Open', function ($ws, $request) {
echo "连接成功";
//连接成功时向客户端推送消息
$ws->push($request->fd, "欢迎\n");
});
//监听WebSocket消息事件
$ws->on('Message', function ($ws, $frame) {
echo "消息: {$frame->data}\n";
//将客户端发送来的消息在推送回去
$ws->push($frame->fd, "server: {$frame->data}");
});
//监听WebSocket连接关闭事件
$ws->on('Close', function ($ws, $fd) {
echo "连接{$fd}断开\n";
});
$ws->start();
再本地环境编写h5代码,实现客户端连接
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket</title>
</head>
<body>
<div id="message"></div>
<div>
<input id="msg" placeholder="清输入消息">
<button id="submit" type="submit">发送</button>
</div>
</body>
</html>
<script>
let message = document.getElementById('message');
let msg = document.querySelector('#msg');
let submit = document.querySelector('#submit');
var wsServer = 'ws://8.131.95.189:6070';
//创建websocket对象
var websocket = new WebSocket(wsServer);
//打开连接时向服务端发送消息
websocket.onopen = (evt) => {
websocket.send('成功连接');
};
//点击发送消息按钮时
submit.onclick = () => {
//向服务端发送消息发送消息
websocket.send(msg.value);
//将输入框赋值为空
msg.value = '';
};
//客户端接收服务端发送请求时
websocket.onmessage = (evt) => {
//将id为message的div添加传递过来消息,一直累加
message.innerHTML += "<p>" + evt.data + "</p>";
};
//连接断开时
websocket.onclose = (evt)=> {
console.log("连接断开");
};
//通信错误时
websocket.onerror = () => {
console.log('Error occured: ' + evt.data);
};
</script>
客户端运行结果,本地号h5页面与服务器进行通信
服务端运行结果