I have this Java WebSocket application here. My code for constructing the URL for the server endpoint is:
function constructWebSocket(endpoint, onMessageCallback) {
const url = constructWebSocketUrl(endpoint);
const socket = new WebSocket(url);
socket.onopen = (event) => {
console.log("onopen. Event: ", event);
};
socket.onmessage = onMessageCallback;
socket.onclose = (event) => {
console.log("onclose. Event: ", event);
};
socket.onerror = (event) => {
console.log("onerror. Event: ", event);
};
return socket;
}
function constructWebSocketUrl(endpoint) {
const host = document.location.host;
const path = document.location.pathname;
const protocol = document.location.protocol;
if (protocol.startsWith("https")) {
return `wss://${host}${path}${endpoint}`;
} else if (protocol.startsWith("http")) {
return `ws://${host}${path}${endpoint}`;
} else {
throw `Unknown protocol: ${protocol}.`;
}
}
(The app is deployed on Heroku.)
While the above snippet returns a valid WebSocket when I run the web app on local Tomcat, on Heroku it returns 404 Not Found
and close code 1006. What am I missing here?
2
Answers
Check if there are any Heroku-specific configurations or restrictions that may affect WebSocket connections. Heroku has some limitations on WebSocket connections, so make sure your application complies with Heroku’s guidelines for WebSocket support.
Ensure that there are no cross-origin issues preventing the WebSocket connection from being established. If your WebSocket server is hosted on a different domain or port than your web application, you may need to configure CORS (Cross-Origin Resource Sharing) headers to allow WebSocket connections from your web application.
Couple thoughts:
(1) Are you following these steps to launch an embedded tomcat on Heroku? How are you launching your Java application in Heroku?
(2) Have you tried one of the examples with websockets like Node/Go I know you have dependencies on other Java projects so that wouldn’t necessarily help you at the end, but it might help elucidate what’s different in the Tomcat setup vs. other languages.