正如问题所暗示的,我想构建一个服务,该服务使用Websocket
在用户之间同步JSON数据。但是,我对websockets
并不陌生,因此需要您的帮助。
我使用以下版本:
前端:角度:9.1.0
后端:Quarkus:1.3.2.Final + Quarkus-undertow-websockets
我在Angular Service中具有以下代码:
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class SocketService {
private ws: any;
constructor() {
}
public connect(): void {
this.ws = new WebSocket('ws://localhost:8080/sync/breit');
this.ws.onmessage = (msg) => {
console.log(msg);
};
}
public sendData(data: any): void {
this.ws.send('/' + name, {}, 'Testmessage');
}
}
当按下按钮时,在ngOninit()
和sendData()
中调用函数连接。
现在,这是后端代码:
package io.sync.websocket;
import org.jboss.logging.Logger;
import javax.enterprise.context.ApplicationScoped;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/sync/{username}")
@ApplicationScoped
public class SyncSocket {
private static final Logger LOG = Logger.getLogger(SyncSocket.class);
Map<String, Session> sessions = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam("username") String username) {
sessions.put(username, session);
}
@OnClose
public void onClose(Session session, @PathParam("username") String username) {
sessions.remove(username);
}
@OnError
public void onError(Session session, @PathParam("username") String username, Throwable throwable) {
sessions.remove(username);
LOG.error("onError", throwable);
}
@OnMessage
public void onMessage(String message, @PathParam("username") String username) {
System.out.println("Message came through");
broadcast(message);
}
private void broadcast(String message) {
sessions.values().forEach(s -> {
s.getAsyncRemote().sendObject(message, result -> {
if (result.getException() != null) {
System.out.println("Unable to send message: " + result.getException());
}
});
});
}
}
我有Quarkus Websocket教程中的这段代码。刚刚修改了一下。
现在,当我按下发送按钮,该按钮在服务中调用了sendData()
函数时,我希望收到Testmessage
,但是我只得到了/
:
Webconsole中的输出:
我不知道如何向Quarkus添加附加的“监听器” URL,我只能定义ServerEndpoint。在Spring Boot中,它是@SendTo('URL_COMES_HERE')
注释。 Quarkus中是否存在类似的东西?
请检查您的sendData方法。我认为数据的行为是“ /”。“名字”从哪里来?此时,它似乎只是一个空字符串。另外,关于“ Testmessage”:如果检查Websocket.send方法,您会发现该方法只有一个参数;否则,将显示为0。因此“ Testmessage”参数将被忽略。