在使用"socket.io": "^2.0.4"
Socket.io初始化如下:
export let io: any;
io = socketio(server,
{
secure: secure,
rejectUnauthorized: false,
},
);
io.set('origins', '*:*');
io.origins('*:*');
io.on('connection', (socket) => {
socket.on('message', async (data) => {
}
}
我想将message
广播到一个房间的所有套接字
所以我做了:
io.to(roomName).emit('message', data);
我记录了io()。到()。emit()没有发出roomName和数据没问题
但message
没有传递任何事件,我错过了什么?
答案 0 :(得分:3)
你的sockect.IO是否在服务器端配置正确,这是一个基于rxjs for Angular的低级套接字服务api,可以使用
import { Injectable } from '@angular/core';
import * as socketio from 'socket.io-client';
import {environment} from '../../../environments/environment';
import {Observable} from 'rxjs/Observable';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Injectable()
export class SocketService {
private socket: SocketIOClient.Socket;
connected$ = new BehaviorSubject<boolean>(false);
constructor() {
this.socket = socketio(environment.socket.baseUrl, environment.socket.config);
this.socket.on('connect', () => this.connected$.next(true));
this.socket.on('disconnect', () => this.connected$.next(false));
}
join(room: string) {
// auto rejoin after reconnect mechanism
this.connected$.subscribe(connected => {
if (connected) {
this.socket.emit('join', {room});
}
});
}
disconnect() {
this.socket.disconnect();
this.connected$.next(false);
}
emit(event: string, data?: any) {
console.group();
console.log('----- SOCKET OUTBAND -----');
console.log('Action: ', event);
console.log('Payload: ', data);
console.groupEnd();
this.socket.emit(event, data);
}
listen(event: string): Observable<any> {
return new Observable( observer => {
this.socket.on(event, data => {
console.group();
console.log('----- SOCKET INBOUND -----');
console.log('Action: ', event);
console.log('Payload: ', data);
console.groupEnd();
observer.next(data);
});
// dispose of the event listener when unsubscribed
return () => this.socket.off(event);
});
}
}
此代码来自 Avatsaev ,感谢他使用套接字Io与NGRX分享他的酷应用程序,你可以看到它与his service code的使用方式
答案 1 :(得分:0)
尝试以下代码:
socket.broadcast.to(roomName).emit('message', data);
答案 2 :(得分:0)
对于遇到类似问题的任何人,请确保您将消息发送到正确的命名空间。就我而言,我需要发送到所有客户端都在收听的“聊天”命名空间,但只发送到特定房间。
例如:
// We still need to specify the namespace, in my case, the "chat" namespace. This is where my clients are listening.
socket.on("special-message", (message) => {
console.log("Special message is: ", message);
socket.to("special").emit("chat", message); // Emit to "special" channel inside the "chat" namespace.
});