|
@@ -0,0 +1,66 @@
|
|
|
+import { App, Inject, OnWSConnection, OnWSDisConnection, OnWSMessage, WSController } from '@midwayjs/decorator';
|
|
|
+import { Context } from '@midwayjs/ws';
|
|
|
+import * as http from 'http';
|
|
|
+import get = require('lodash/get');
|
|
|
+import { Application } from '@midwayjs/ws';
|
|
|
+import last = require('lodash/last');
|
|
|
+@WSController('*/ws/*')
|
|
|
+export class WsSocketController {
|
|
|
+ @Inject()
|
|
|
+ ctx: Context;
|
|
|
+ @App('webSocket')
|
|
|
+ wsApp: Application;
|
|
|
+
|
|
|
+ @OnWSConnection()
|
|
|
+ async onConnectionMethod(socket: Context, request: http.IncomingMessage) {
|
|
|
+ const url = get(request, 'url');
|
|
|
+ const arr = url.split('/');
|
|
|
+ const token = last(arr);
|
|
|
+ socket.send('connect success');
|
|
|
+ const acs = this.getClients();
|
|
|
+ // 最后一个是该websocket实例,赋上token
|
|
|
+ const client = last(acs);
|
|
|
+ client.token = token;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 获取信息
|
|
|
+ @OnWSMessage('message')
|
|
|
+ async gotMessage(data: Buffer) {
|
|
|
+ // const msg = data.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ @OnWSDisConnection()
|
|
|
+ async disconnect(id) {
|
|
|
+ // 断开连接
|
|
|
+ }
|
|
|
+ /**
|
|
|
+ * 给指定对象发送消息
|
|
|
+ * @param data 要发送的数据
|
|
|
+ * @param token 店铺id/用户id
|
|
|
+ */
|
|
|
+ async toSend(data: object, token) {
|
|
|
+ const clients = this.getClient(token);
|
|
|
+ if (!clients) return;
|
|
|
+ clients.send(JSON.stringify(data));
|
|
|
+ }
|
|
|
+ /**
|
|
|
+ * 获取所有连接实例
|
|
|
+ */
|
|
|
+ getClients(): Array<any> {
|
|
|
+ const acs = [];
|
|
|
+ const clients = this.wsApp.clients;
|
|
|
+ clients.forEach(e => {
|
|
|
+ acs.push(e);
|
|
|
+ });
|
|
|
+ return acs;
|
|
|
+ }
|
|
|
+ /**
|
|
|
+ * 获取指定实例连接
|
|
|
+ * @param token 用户id/店铺id
|
|
|
+ */
|
|
|
+ getClient(token: string) {
|
|
|
+ const clients = this.getClients();
|
|
|
+ const client = clients.find(f => f.token === token);
|
|
|
+ return client;
|
|
|
+ }
|
|
|
+}
|