nginx+thinkphp 做个长链接服务

thinkphp 启动个服务   

php think worker

默认端口  http://localhost:2346

 

nginx 配置

http {

  upstream http_backend {
    keepalive 16;
    server 127.0.0.1:2346;
  }

  server{
    listen 80;
    server_name www.myphp.com;
    client_body_buffer_size 10m;
    client_max_body_size 10m;

    location / {
      root D:/gitee/ysq/yiqi/yiqi-tp6/public;
      index index.php index.html index.htm;
      if (!-e $request_filename) {
        rewrite ^/index.php(.*)$ /index.php?s=$1 last;
        rewrite ^(.*)$ /index.php?s=$1 last;
        break;
      }
    }

    location ~ \.php$ {
      root D:/gitee/ysq/yiqi/yiqi-tp6/public;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      include fastcgi_params;
    }

    location /http/ {
      proxy_pass http://http_backend;
      proxy_http_version 1.1; #设置http版本为1.1
      proxy_set_header Connection ""; #设置http头默认为长连接,不关闭
    }

  }

}

前端调用

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="/index/default/js/jquery.min.js"></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>

<body>
<div id="app">{{ message }}
<a @click="send">发送</a>

</div>
<button id="SendBtn">发送数据到服务器</button>

<script>
const { createApp } = Vue

createApp({
data() {
return {
message: 'Hello Vue!',
// websocket对象
ws: null
}
},
created() {
const _that = this;
// 客户端(浏览器)websocket
this.ws = new WebSocket("ws://www.myphp.com/http/"); // 创建一个websocket,同时,发送连接到服务器
this.ws.onopen = function () {
// http握手完成
console.log("连接已建立");
setInterval(function () {
_that.ws.send(JSON.stringify({ 'type': "peng" }));
console.log('发送心跳...');

}, 30000)
};

this.ws.onmessage = function (e) {
console.log("来自服务器的数据", e.data);
};

this.ws.onclose = function () {
console.log("通道关闭");
};

document.querySelector("button").onclick = function () {
console.log("发送");
_that.ws.send("123");
};
},
methods: {

/**
* 发送
*/
send() {
console.log(44444);
}

}
}).mount('#app')
</script>
</body>

</html>

posted @ 2023-08-26 23:37  luoyiming  阅读(75)  评论(0)    收藏  举报