Java 如何在嵌入式tomcat中以编程方式添加websocket端点?
几周来,我一直试图让WebSocket与嵌入式tomcat一起工作。我曾尝试在tomcat单元测试中模拟这些示例,但没有效果。这是我第一次尝试使用WebSocket,所以我可能犯了一个愚蠢的错误。有没有人有嵌入式tomcat WebSocket的简单“回声”示例Java 如何在嵌入式tomcat中以编程方式添加websocket端点?,java,tomcat,embedded-tomcat-7,Java,Tomcat,Embedded Tomcat 7,几周来,我一直试图让WebSocket与嵌入式tomcat一起工作。我曾尝试在tomcat单元测试中模拟这些示例,但没有效果。这是我第一次尝试使用WebSocket,所以我可能犯了一个愚蠢的错误。有没有人有嵌入式tomcat WebSocket的简单“回声”示例 public void run() { if(!new File(consoleAppBase).isDirectory()) { consoleAppBase = Paths.get("").toA
public void run() {
if(!new File(consoleAppBase).isDirectory())
{
consoleAppBase = Paths.get("").toAbsolutePath().toString() + File.separatorChar + "wepapp";
}
tomcat = new Tomcat();
tomcat.getService().removeConnector(tomcat.getConnector()); // remove default
tomcat.getService().addConnector(createSslConnector(ConfigManager.getWeb_securePort())); // add secure option
StandardServer server = (StandardServer) tomcat.getServer();
AprLifecycleListener listener = new AprLifecycleListener();
server.addLifecycleListener(listener);
try {
SecurityConstraint constraint = new SecurityConstraint();
constraint.setDisplayName("SSL Redirect Constraint");
constraint.setAuthConstraint(true);
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
constraint.addAuthRole("administrator");
constraint.addCollection(collection);
//create the console webapp.
consoleContext = tomcat.addWebapp(consoleContextPath, consoleAppBase);
consoleContext.addConstraint(constraint);
//this allows that little login popup for the console webapp.
LoginConfig loginConfig = new LoginConfig();
loginConfig.setAuthMethod("BASIC");
consoleContext.setLoginConfig(loginConfig);
consoleContext.addSecurityRole("administrator");
//this creates a valid user.
tomcat.addUser(ConfigManager.getWeb_username(), Encryptor.decrypt(ConfigManager.getWeb_passwordEncrypted()));
tomcat.addRole("admin", "administrator");
} catch (ServletException e) {
LogMaster.getWebServerLogger().error("Error launching Web Application. Stopping Web Server.");
LogMaster.getErrorLogger().error("Error launching Web Application. Stopping Web Server.", e);
return;
}
addServlets(); // this is where I usually call a convenience method to add servlets
// How can I add websocket endpoints instead?
}
据我所知,配置websocket与配置servlet(或servlet过滤器)是一样的。在web.xml中,必须包含
true
我假设java配置中有一个类似的标志。我是这样使用WebSocket的:
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
//...
@ServerEndpoint("/move")
public class TestWebSocketEndPoint {//@OnMessage
public void onMessage(Session session, String message) {}
private static final Queue<Session> QUEUE = new ConcurrentLinkedQueue<Session>();
@OnOpen
public void open(Session session) {
QUEUE.add(session);
}
@OnError
public void error(Session session, Throwable t) {
StaticLogger.log(TestWebSocketEndPoint.class, t);
QUEUE.remove(session);
}
@OnClose
public void closedConnection(Session session) {
QUEUE.remove(session);
}
public static void sendToAll(String message) throws IOException {
ArrayList<Session> closedSessions = new ArrayList<Session>();
for (Session session : QUEUE) {
if (!session.isOpen()) {
closedSessions.add(session);
} else {
session.getBasicRemote().sendText(message);
}
}
QUEUE.removeAll(closedSessions);
}
}
Java调用:
TestWebSocketEndPoint.sendToAll(result);
对于编程(非注释)端点,必须提供一个实现Endpoint
的类作为服务器端,然后:
ServerApplicationConfig
,提供有关WAR文件中找到的一些或所有未注释的Endpoint
实例的EndpointConfig
信息,或ServerContainer.addEndpoint()
看到Java了吗™ WebSocket的API,JSR356。我的答案中的代码只在Tomcat8上运行良好。在您的帮助下,我能够让它在Tomcat7中运行。非常感谢它在Tomcat 7.0.41或42上工作。这不是以编程方式添加端点,而是由
ServerContainer
自动添加的带注释的端点。配置WebSocket与配置servlet或servlet过滤器不同 TestWebSocketEndPoint.sendToAll(result);