【发布时间】:2021-01-16 15:34:26
【问题描述】:
经过努力,我设法将客户端与 tomcat 服务器通信。我终于在服务器的handleMessage 中收到了消息。我现在必须更新index.jsp 文件的内容以添加收到的消息。
这是我的服务器 java 类:
package network.server;
import javax.enterprise.context.ApplicationScoped;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
@ApplicationScoped
@ServerEndpoint("/status")
public class WebSocket {
private Set<Session> sessions = new HashSet<>();
private Session session;
@OnOpen
public void onOpen(Session session){
System.out.println("Session opened in WebSocket ");
this.session = session;
sessions.add(session);
}
@OnMessage
public void handleMessage(String message) {
if (session.isOpen() && session != null){
try {
System.out.println("Received this message in the server: " + message);
//TODO edit jsp
session.getBasicRemote().sendText("This is a totally unnecessary answer from the server.");
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("Session is not opened or null");
}
}
@OnClose
public void close(Session session) {
System.out.println("Session closed ==>");
sessions.remove(session);
}
@OnError
public void onError(Throwable e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
index.jsp 是默认的:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>My title</title>
</head>
<body>
Hello world!
</body>
</html>
我怎样才能做到这一点?
【问题讨论】:
标签: java jsp web tomcat websocket