每当发出请求时,应用程序都应该更新表.我有以下代码来接收来自服务器的通知.当我运行该应用程序时,它在警报框中显示以下内容,似乎已连接,但当我调用通知类的“发送”方法时,它没有任何改变.
警报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);
}
}
马文
<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");
};