【发布时间】:2016-01-28 08:54:03
【问题描述】:
我已经尝试了数周来让 websockets 与嵌入式 tomcat 一起工作。我尝试在 tomcat 单元测试中模拟示例无济于事。这是我第一次尝试使用 websockets,所以我可能会犯一个愚蠢的错误。有没有人有嵌入式 tomcat websockets 的简单“Echo”示例?
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?
}
【问题讨论】:
-
我的回答中的代码仅在 Tomcat 8 上运行良好。
-
在您的帮助下,我能够让它在 Tomcat 7 中工作。非常感谢
-
它适用于 Tomcat 7.0.41 或 42 左右。
标签: java tomcat embedded-tomcat-7