我是一个应用程序,我想在其中保持心跳以检查我的浏览器是否已连接。所以为此我实现了一个网络套接字。我在后端使用 java,在前端使用 angular 5。
我的代码片段java
@ServerEndpoint(value = "/endpoint", configurator = HttpSessionConfigurator.class)
public class WebServer {
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
log.debug("on open session: "+ session.getId());
this.httpSession = (HttpSession) config.getUserProperties().get(IBClientConstants.HTTP_SESSION);
}
@OnClose
public void onClose(Session session) {
log.debug("onClose session: "+ session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
String data = "success";//i send some data which is needed in UI
session.getBasicRemote().sendText(data);
}
@OnError
public void onError(Throwable t) {
log.debug(t.getMessage());
}
}
我的角边代码:
@Injectable()
export class WebSocketClient {
private webSocket;
private websocketUrl;
constructor(private appConfig: AppConfig) {
this.websocketUrl = appConfig.getBaseURLWithContextPath();
if (this.websocketUrl) {
this.websocketUrl = this.websocketUrl.replace("http", "ws") + "/endpoint"
}
this.webSocket = new WebSocket(this.websocketUrl);
}
connect() {
try {
this.webSocket.onopen = (event) => {
console.log('onopen::' + JSON.stringify(event, null, 4));
}
this.webSocket.onmessage = (event) => {
var response = event.data;
let jsonData = JSON.parse(response);
//i use this data
}
所有功能都运行良好。但是当我使用 https 连接时,这意味着我的 websocket url 变为 wss://localhost:8443/InBetween/endpoint。此时,如果我在 chrome 中刷新浏览器,它会在控制台中抛出异常。
侃侃尔雅
慕桂英4014372
相关分类