[Support] 我需要在http服务里调用socket服务的api,向某个房间传递信息,但是不知道该怎么实现 #3733
Unanswered
celiu12345
asked this question in
Q&A
Replies: 2 comments 2 replies
-
1、不要试图在 service 中注入 Controller,层级反转了,你应该单独抽一个消息中转、处理的通用服务 |
Beta Was this translation helpful? Give feedback.
1 reply
-
import { App, Init, Inject, OnWSConnection, OnWSMessage, WSController, sleep } from "@midwayjs/core";
import { Application, Context } from "@midwayjs/socketio";
@WSController('/')
export class WSMessageController {
@Inject()
socket: Context;
@App('socketIO')
socketApp: Application;
@Init()
async init() {
// 加入一个房间
this.socket.join('room1');
}
@OnWSConnection()
async onConnection() {
console.log('socket connected: ' + this.socket.id);
}
@OnWSMessage('message')
onMessage(msg) {
console.log('got in OnWSMessage: ' + this.socket.id + ':' + msg); // 这里也收不到
if (msg === 'abc') {
// 注意,当前的 socket 发送房间消息,不会发送给当前自己的连接
this.socket.in("room1").emit("hello", `Everybody in room1 from ${this.socket.id}`);
} else if (msg === 'all') {
// 注意,使用全局对象发送,这里会发送给所有,包括自己
this.socketApp.in("room1").emit("hello", `Everybody in room1 from ${this.socket.id}`);
} else {
this.socket.emit('hello', `only you from ${this.socket.id}`);
}
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Describe the problem(描述问题)
这是我的socket代码,我需要在用户通过http提交任务之后,向某个连接socket的设备发送一条开始工作的指令,以下是我在http服务里的代码:
我可以确定已经通过设备连接并创建了socket房间,但当我在http里调用sendMessageToDevice的时候,控制台打印出的socketMap是{},请各位大佬帮忙看看,无比感谢
Midway Versions(Midway 版本)
[email protected]
Beta Was this translation helpful? Give feedback.
All reactions