我正试图按照本教程中给出的说明,在Netbeans中创建一个示例应用程序。我已到达测试部分。当我在chrome中运行应用程序时,它显示
到的WebSocket连接"ws://localhost:8080/WhiteboardApp/whiteboardendpoint"失败:错误在WebSocket握手期间:意外的响应代码:404
index.html
<!DOCTYPE html>
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Collaborative Whiteboard App</h1>
<div id="output"></div>
<script type="text/javascript" src="websocket.js"></script>
</body>
</html>
websocket.js
var wsUri = "ws://" + document.location.host + document.location.pathname + "whiteboardendpoint";
var websocket = new WebSocket(wsUri);
websocket.onerror = function(evt) { onError(evt) };
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
// For testing purposes
var output = document.getElementById("output");
websocket.onopen = function(evt) { onOpen(evt) };
function writeToScreen(message) {
output.innerHTML += message + "<br>";
}
function onOpen(evt) {
writeToScreen("Connected to " + wsUri);
}
// End test functions
MyWhiteboard.java
package org.myapps.whiteboardapp;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/whiteboardendpoint ")
public class MyWhiteboard {
private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());
@OnMessage
public String onMessage(String message) {
return null;
}
@OnOpen
public void onOpen (Session peer) {
peers.add(peer);
}
@OnClose
public void onClose (Session peer) {
peers.remove(peer);
}
}
我哪里错了?我该如何解决这个问题?
您有一个无效的服务器注释
修复此
@ServerEndpoint("/whiteboardendpoint ")
至
@ServerEndpoint("/whiteboardendpoint") /* removed space */
按照目前的定义方式,您可能只需将javascript wsUri
定义更改为。。。
var wsUri = "ws://" + document.location.host + document.location.pathname +
"whiteboardendpoint%20";
var websocket = new WebSocket(wsUri);
让它发挥作用。(刚刚添加了一个URI编码空间)