Vue websocket+thinkphp6

文章描述:

  安装 composer require topthink/think-worker   […]

 

安装

composer require topthink/think-worker

 

后端

注意:创建多应用

composer require topthink/think-multi-app

 

在app下创建http目录,新建Worker.php,代码如下:

<?php
namespace app\http;

use think\worker\Server;
class Worker extends Server
{
    protected  $socket = 'http://0.0.0.0:2346';

    public function onMessage($connection,$data)
    {
        file_put_contents('success_log.txt', date('Y-m-d H:i:s') . ' - ' . 'success info ' . $data . "\n", FILE_APPEND);

        $connection->send(json_encode($data));
    }
}

 

在config目录worker_server.php中增加配置参数:

 

'worker_class'=>'app\http\Worker',

 

 

在phpstrom运行以下命令:

php think worker:server

 

 

Vue


<template>
  <div id="app">
    <div class="container" :style="{backgroundColor:present.color}">{{present.text}}</div>
	<div>
		<input v-model="text" />
	</div>
    <button class="btn" @click="toSend">向服务器发送数据</button>
  </div>
</template>
 
<script>
// const path = "ws://localhost:3000/socket"
const path = "ws://127.0.0.1:2346"
export default {
  name: 'App',
  data(){
    return {
      socket:null,
      present:{
        color:'#172b4d',
        text:'默认文本'
      },
      heartCheck:{
        timeout: 1000*60*5, //五分钟心跳一次
        timer:null,
        serverTimer:null,
        reset:()=>{
          clearTimeout((this.heartCheck.timer))
          clearTimeout((this.heartCheck.serverTimer))
          return this.heartCheck
        },
        start:()=>{
            this.heartCheck.serverTimer = setInterval(()=>{
              if(this.socket.readyState===1){
                console.log('虽然没有发送消息,但是现在是连接状态');
                this.socket.send('socket heart')
                this.heartCheck.reset().start()
              }else{
                console.log('已断开连接,尝试重连吧');
                this.socketReconnect()
              }
          },this.heartCheck.timeout)
        }
      },
      reconnectTimer:null,// 重连计时器
      reconnectLock:false,// 重连的锁
	  text:''
    }
  },
  mounted(){
    if (typeof (WebSocket) === 'undefined') { console.error('浏览器不支持WebSocket'); return; }
    try {
      this.initSocket()
    } catch (error) {
      // 重连
      console.log('出来');
      this.socketReconnect()
    }
  },
  beforeDestroy(){
    this.socket.close()
  },
  methods:{
    initSocket(){
      this.socket = new WebSocket(path)
      this.socket.onopen = this.openHandler // 连接成功建立的回调
      this.socket.onmessage = this.messageHandler // 接收到消息的回调
      this.socket.onerror = this.errorHandler // 连接发生错误的回调
      this.socket.onsend = this.sendHandler // 向后端发送数据的回调
      this.socket.onclose = this.closeHandler // 连接关闭的回调
      
      window.onbeforeunload = () => {
        this.socket.close()  // 窗口关闭时主动断开请求 
      };
    },
    socketReconnect(){
      if (this.reconnectLock) {
          return;
      }
      this.reconnectLock = true
      this.reconnectTimer && clearTimeout(this.reconnectTimer);
      this.reconnectTimer = setTimeout(() => {
          console.log("WebSocket:重连中...");
          this.reconnectLock = false;
          // websocket启动
          this.initSocket();
        }, 4000);
    },
    // 连接成功
    openHandler(){
      this.heartCheck.reset().start();// 建立心跳
    },
    // 接收到服务器信息
    messageHandler(res){
      this.present.color = JSON.parse(res.data).color
      this.present.text = JSON.parse(res.data).text
      this.heartCheck.reset().start() // 初始化心跳时间并重新开始心跳。如果能正常通信,无须心跳检测
	  console.log(res)
	  
    },
    // 连接错误,重连
    errorHandler(){
      console.log('错误');
      this.socketReconnect()
    },
    // 向后端发送数据的回调
    sendHandler(){
		
	},
    // 连接关闭的回调
    closeHandler(){
      this.heartCheck.reset();
    },
    // 带年纪按钮触发,向服务器发送数据
    toSend(){
		let text = this.text
		// this.socket.send('我是浏览器端发送的数据')
		this.socket.send(text)
    }
  }
}
</script>
 
<style lang="scss">

</style>

 

php

protected $socket = ‘http://localhost:2346’;

 

vue

const path = “ws://localhost:2346”

 

在线测试地址:https://www.easyswoole.com/wstool.html

发布时间:2024/04/04

发表评论