我有以下针对websockets的测试html页面
<!DOCTYPE html>
<html>
<head>
<title>Apache Tomcat WebSocket Example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var ws = null;
var target = 'ws://some_ip_addr:8080/gameserv-1.0/endpoint';
function connect() {
if ('WebSocket' in window) {
ws = new WebSocket(target);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(target);
} else {
alert('WebSocket is not supported by this browser.');
return;
}
ws.onopen = function() {
log('Info: WebSocket connection opened.');
};
ws.onmessage = function(event) {
log('Received: ' + event.data);
};
ws.onclose = function() {
log('Info: WebSocket connection closed.');
};
}
function disconnect() {
if (ws != null) {
ws.close();
ws = null;
}
// setConnected(false);
}
function log(message) {
$("#mydiv").append($("<p>").text(message));
}
function testButtonSend() {
var message = {
'commandType': 'TEST',
'command': 'AUCTIONLIST'
};
ws.send(message);
}
$(document).ready(function() {
connect();
});
</script>
</head>
<body>
<div id="mydiv">
<input type="button" onclick="testButtonSend()">
</div>
</body>
</html>
&#13;
负责此websocket的java类是:
@ServerEndpoint("/endpoint")
public final class Websocket {
Gson gson = new Gson();
private boolean connectionOpen;
private Session session;
public Websocket(int byteBufferMaxSize, int charBufferMaxSize) {
super();
setConnectionOpen(false);
}
@OnOpen
public void onOpen(final Session session, EndpointConfig config) {
this.connectionOpen = true;
this.session = session;
}
@OnClose
public void close(Session session,
CloseReason reason) {
this.connectionOpen = false;
this.session = null;
}
@OnMessage
public void onTextMessage(Session session, String message) throws IOException {
MessageFromClientAPI messageFromClient = gson.fromJson(message, MessageFromClientAPI.class);
Integer pID = messageFromClient.getpID();
....
}
public boolean send(MessageToClientAPI message) {
if (!connectionOpen)
return false;
try {
session.getBasicRemote().sendText(gson.toJson(message));
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public boolean isConnectionOpen() {
return connectionOpen;
}
public void setConnectionOpen(boolean connectionOpen) {
this.connectionOpen = connectionOpen;
}
}
问题是连接在打开后立即关闭。此外,调试器不会停止onOpen方法(以及任何其他方法)。
错误是什么?
答案 0 :(得分:1)
问题已解决。它的原因是在构造函数中。这是不正确的。我刚删除它,现在它可以工作了。