# websocket

1.在src->config->extend.js 添加

const websocket = require('think-websocket');
module.exports = [
  websocket(think.app)
];

1
2
3
4
5
  1. 在src->config->adapter.js
点击查看adapter.js配置
    const socketio = require('think-websocket-socket.io');


exports.websocket = {
  type: 'socketio',
  common: {
    // common config
  },
  socketio: {
    handle: socketio,
    path: '/socket.io',             // 默认 '/socket.io'
    adapter: null,                  // 默认无 adapter
    messages: {
      open: '/websocket/index/open',       // 建立连接时处理对应到 websocket Controller 下的 open Action
      close: '/websocket/index/close',     // 关闭连接时处理的 Action
      addUser: '/websocket/index/addUser', // addUser 事件处理的 Action
      faSong:"/websocket/index/faSong",
      InboundHangUp:"/websocket/index/InboundHangUp",
      ChangingMessageState:"/websocket/index/ChangingMessageState",
      
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

最后在 src->controller->websocket->index.js

/** 三个Action 要和adapter.js的websocket.socketio.messages 对应*/
 openAction() {
    this.broadcast('username',{age:30}) // 向 socket 广播事件
    this.emit("opend", "websocket连接成功..."); // 单向广播事件
    this.wsData // 获取客户端传过来的数据
    this.websocket  // "获取当前 WebSocket 对象"
    this.isWebsocket // 判断当前请求是否是 WebSocket 请求
  }

  closeAction() {
    console.log("客户端关闭了这里会收到消息");
  }

  addUserAction() {
  }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

websocketAction里的this下面的对象参数说明

参数 说明 类型 示例
broadcast 向 socket 广播事件 Object this.broadcast('username',{age:30})
emit 单向广播事件 Object this.emit("opend", "websocket连接成功...");
wsData 获取客户端传过来的数据 Object -
websocket 获取当前 WebSocket 对象 - -
isWebsocket 判断当前请求是否是 WebSocket 请求 - -

vue客户端调用

1.在index.html

 <script src="//lib.baomitu.com/socket.io/2.0.1/socket.io.js"></script>
<script>
   window.socket = io("https://duxinggj.com");
      window.socket.on("opend", function (data) {
        console.log("opend:", data);
      });
</script>
1
2
3
4
5
6
7

在公告方法或页面上引用

// 监听服务端发来的 this.broadcast('username',{age:30})  username为变量
window.socket.on(`${userName}`, function (data) {
     console.log(userName + ":", data);
})

// 发送消息到服务器

  window.socket.emit("faSong", {
    destName: destName.value,
    fromName: localStorage.userNmae,
    msgBody: MSgjs,
  });

1
2
3
4
5
6
7
8
9
10
11
12
13