Adds an event listener to the namespace specified by the annotation#932
Adds an event listener to the namespace specified by the annotation#932588q9 wants to merge 1 commit into
Conversation
|
You can do it by yourself, in my projects I add: /**
* Types that carry this annotation are treated as namespace event listeners.
* Class should contain methods annotated with:
* {@link com.corundumstudio.socketio.annotation.OnConnect @OnConnect}
* {@link com.corundumstudio.socketio.annotation.OnDisconnect @OnDisconnect}
* {@link com.corundumstudio.socketio.annotation.OnEvent @OnEvent}
* @see AppServerEventListener
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Namespace {
/**
* The value decides to which namespace current listener should be attached,
* the same value can be reused to a few listeners
*/
String value() default DEFAULT_NAME; // ""
}
/**
* A class that listens for application/context events.
* Registers socket.io namespace listeners and shuts down the server
* */
@Slf4j
@Component
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = PRIVATE)
public class AppServerEventListener {
SocketIOServer socketIOServer;
@EventListener(ApplicationReadyEvent.class)
public void registerNamespacesEventListeners(ApplicationReadyEvent readyEvent) {
ConfigurableApplicationContext applicationContext = readyEvent.getApplicationContext();
Map<String, Object> beansWithNamespace = applicationContext.getBeansWithAnnotation(Namespace.class);
if (beansWithNamespace.isEmpty()) {
log.warn("No socket.io namespace listeners found");
}
beansWithNamespace.forEach((beanName, bean) -> Optional.ofNullable(
applicationContext.findAnnotationOnBean(beanName, Namespace.class)
).ifPresent(namespace -> {
socketIOServer
.addNamespace(namespace.value())
.addListeners(bean, bean.getClass());
log.info("{} listener added to {} socket.io namespace", beanName, namespace.value());
})
);
}
@EventListener(ContextClosedEvent.class)
public void shutDownSocketIOServer() {
socketIOServer.stop();
}
}Then you can create classes annotated with |
wow!this look like is a good combine with spring,but what is function of namespace ?I think that can use for distinctive function of socket |
|
Namespace just logically groups sockets(each of them can be connected to many namespaces, at least to the default ("/") one, which contains all sockets). In most cases you can just use the default one and group sockets by rooms (also you can add distinctive parametrs to socket) |
my application requirement need let namespace for more useful,so I add that code for title statement uitlity,if have any problem about destroy hook or more that,I will listen carefully to your advice.