I've been trying for weeks to get websockets working with embedded tomcat. I've tried emulating the examples in the tomcat unit tests to no avail. This is the first time I've tried to use websockets so I'm likely making a foolish mistake. Does anyone have any simple "Echo" examples for embedded tomcat websockets?
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?
}
For programmatic (non-annotated) endpoints, you have to provide a class that implements Endpoint
to act as the server end, and then either:
ServerApplicationConfig
in your WAR file, that supplies EndpointConfig
information about some or all of the non-annotated Endpoint
instances that were found in the WAR file, orServerContainer.addEndpoint()
during the deployment phase of your webapp.See the Java™ API for WebSocket, JSR 356.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With