我正在尝试按照this tutorial中的说明操作,并在Netbeans中创建一个示例应用程序。我已到达测试部分。当我在chrome中运行应用程序时,它说
WebSocket连接到 ' WS://本地主机: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);
}
}
我哪里出错了?我该如何解决这个问题?
答案 0 :(得分:0)
您的服务器注释无效
修复此问题
@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编码空间)