我正在尝试使用 websockets 创建 javaee 应用程序,但是无法使程序正常工作。使用 Tomcat 7、带有 websockets 的 Java EE 7 应用程序。
这是我的java代码:
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) {
//Connection opened.
System.out.println("EchoEndpoint on open");
endpoint = session.getAsyncRemote();
}
@OnMessage
public void onMessage(Session session, String msg) {
//Message received.
System.out.println("EchoEndpoint on message");
}
@OnError
public void error(Session session, Throwable error) {
//Connection error.
System.out.println("EchoEndpoint on error");
}
@OnClose
public void close(Session session, CloseReason reason) {
//Connection closed.
System.out.println("EchoEndpoint on close");
}
public void send(String string) {
System.out.println("Send called to EchoEndpoint");
endpoint.sendText(string);
}
}
网页.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>
索引.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>');
//websocket.close();
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
</html>
在客户端尝试执行时:
websocket = 新的 WebSocket(wsUri);
我得到:
到 ws://localhost:8080/myapp/hello 的 Websocket 连接失败:意外响应代码:404
我是否错过了 web.xml 或其他地方的某些内容?