Reputation: 4302
I have the following test html page for websockets
<!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>
The java class responsible for this websocket is:
@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;
}
}
The problem is that connection is closed immediately after it is opened. Moreover, debugger is not stopping on the onOpen method (and any other methods too).
What is the mistake?
Upvotes: 0
Views: 1409
Reputation: 4302
Problem resolved. The cause of it was in the constructor. It was incorrect. I just removed it and now it works.
Upvotes: 1