I am trying to create a javaee application with websockets but cannot get the program to work correctly. Using the Tomcat 7, Java EE 7 application with websites.
Here is my Java code:
import javax.websocket.CloseReason; import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.RemoteEndpoint; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value="/hello") public class EchoEndpoint { RemoteEndpoint.Async endpoint; @OnOpen public void open(Session session, EndpointConfig conf) {
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> </web-app>
index.html
<!DOCTYPE html> <meta charset="utf-8" /> <title>WebSocket Test</title> <script language="javascript" type="text/javascript"> var wsUri = "ws://localhost:8080/myapp/hello"; var output; function init() { output = document.getElementById("output"); testWebSocket(); } function testWebSocket() { websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onclose = function(evt) { onClose(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; } function onOpen(evt) { writeToScreen("CONNECTED"); doSend("WebSocket rocks"); } function onClose(evt) { writeToScreen("DISCONNECTED"); } function onMessage(evt) { writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>'); </script> <h2>WebSocket Test</h2> <div id="output"></div> </html>
On the client side, when trying to execute:
websocket = new WebSocket (wsUri);
I get:
Websocket connection with ws: // localhost: 8080 / myapp / hello failed: Unexpected response code: 404
Am I missing something in web.xml or somewhere else?
source share