[英]Can not establish a WebSocket connection from JavaScript
應用程序應該在發出請求時更新表。 我有以下代碼來接收來自服務器的通知。 當我運行應用程序時,它在警告框中顯示以下內容,似乎已連接但是當我調用通知類的“發送”方法時它不會改變任何內容。
警報1)
windowfunction connect() {
wsocket = new WebSocket("ws://localhost:8080/Notifications");
alert("got connected");
document.getElementById("foo").innerHTML = "arraypv[0]";
wsocket.onmessage = onMessage;
}
警報2)
got connected
JavaScript的
<script type="text/javascript">
var wsocket;
function connect() {
wsocket = new WebSocket("ws://localhost:8080/Notifications");
alert("got connected");
wsocket.onmessage = onMessage;
}
function onMessage(evt) {
alert(evt);
var arraypv = evt;
alert("array" + arraypv);
document.getElementById("foo").innerHTML = arraypv[0];
}
alert("window" + connect);
window.addEventListener("load", connect, false);
</script>
碼
@ServerEndpoint("/Notifications")
public class Notifications {
/* Queue for all open WebSocket sessions */
static Queue<Session> queue = new ConcurrentLinkedQueue();
public static void send() {
System.err.println("send");
String msg = "Here is the message";
try {
/* Send updates to all open WebSocket sessions */
for (Session session : queue) {
session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@OnOpen
public void openConnection(Session session) {
System.err.println("in open connection");
queue.add(session);
}
@OnClose
public void closedConnection(Session session) {
System.err.println("in closed connection");
queue.remove(session);
}
@OnError
public void error(Session session, Throwable t) {
System.err.println("in error");
queue.remove(session);
}
}
Maven的
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0-b08</version>
</dependency>
要發送消息,我在我的一個函數中使用以下代碼
Notifications.send();
控制台只顯示
嚴重:發送
當我使用FireBug跟蹤連接時,它會顯示
Firefox can't establish a connection to the server at ws://localhost:8080/Notifications.
你忘記了斜杠 :你應該連接到
ws://localhost:8080/Notifications/
代替
ws://localhost:8080/Notifications
(注意尾部斜線,這非常重要)。
此外,您的代碼還有一些問題。 WebSocket就像 - 幾乎所有javascript中的異步一樣。 在你做你的時間點
alert("got connected");
websocket不是動態連接的。 請像這樣附上一個事件處理程序
wsocket.onopen = function() {
alert("got connected");
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.