tp5.1简单聊天室

首先要下载worker=>composer require topthink/think-worker=2.0.*在这里插入图片描述
在这里插入图片描述
命令行运行:php think worker:server
这样,websocket就启动了,如下:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

说这么多,当然是要代码的啦

<?php

namespace app\http;

use think\worker\Server;

class Worker extends Server
{
    protected $socket = 'http://192.168.150.100:8888';
    static $uidConnections = [];
    public function onMessage($connection, $data)
    {
        if (!in_array($connection,self::$uidConnections)) {
            array_push(self::$uidConnections,$connection);
        }
        foreach (self::$uidConnections as $person) {
            $person->send($data);
        }
    }
}
<template>
  <div id="app">
    <el-input v-model="value" type="text" @keyup.enter.native="Send" placeholder="聊天内容"></el-input>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: "",
      ws: "",
    };
  },
  created() {
    this.ws = new WebSocket("ws://192.168.150.100:8888");
    this.ws.onopen =  ()=> {
      console.log("连接成功");
      this.ws.send("hello,thinkphp");
    };
    this.ws.onmessage =  (e)=> {
      this.$message(e.data)
    };
  },
  methods: {
    Send() {
      this.ws.send(this.value);
    },
  },
};
</script>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页