I am establishing WebSocket connectivity where the server is built using javax.websocket
and the client is in JavaScript.
This code is working fine. But after some time session is closed. I want to keep this session alive.
I have two questions:
- If this connection is getting closed because of session idle time out
- How to keep this session alive.
Following is the JavaScript code:
var wsUri="ws://localhost/";
var websocket = new WebSocket(wsUri);
var datasocket;
var username;
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
function join() {
username = textField.value;
websocket.send(username + " joined");
console.log("joined");
}
function send_message() {
websocket.send(username + ": " + textField.value);
}
function onOpen() {
console.log("connected to url");
websocket.send("Hello");
// writeToScreen("Connected to " + wsUri);
}
function onMessage(evt) {
var res = {};
console.log("onMessage: " + evt.data);
if (evt.data.indexOf("joined") != -1) {
} else {
datasocket=evt.data
//getLatestData();
res = JSON.parse(event.data);
$scope.Impact = res["Impact"];
$scope.Temperature = res["Temperature"];
$scope.Humidity = res["Humidity"];
}
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function writeToScreen(message) {
// output.innerHTML += message + "<br>";
}
function onClose(evt)
{
console.log("Disconnected");
}
And Java code is following:
@javax.websocket.server.ServerEndpoint("/")
public class Endpoint {
private static Queue<Session> queue = new ConcurrentLinkedQueue<Session>();
static StringBuilder sb = null;
ByteArrayOutputStream bytes = null;
@OnMessage
public void onMessage(Session session, String msg) {
// provided for completeness, in out scenario clients don't send any msg.
try {
// System.out.println("received msg "+msg+" from "+session.getId());
sendAll(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void sendAll(String msg) {
JSONParser parser = new JSONParser();
Object obj = null ;
try {
obj = parser.parse(msg);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;
if (sb == null) {
sb = new StringBuilder();
}
sb.append(jsonObject.toString());
// System.out.println(jsonObject.toJSONString());
try {
/* Send the new rate to all open WebSocket sessions */
ArrayList<Session > closedSessions= new ArrayList<>();
for (Session session : queue) {
if(!session.isOpen()) {
System.err.println("Closed session: "+session.getId());
closedSessions.add(session);
}
else {
session.getBasicRemote().sendText(msg);
}
}
queue.removeAll(closedSessions);
// System.out.println("Sending "+msg+" to "+queue.size()+" clients");
} catch (Throwable e) {
e.printStackTrace();
}
sb = null;
}
@OnOpen
public void open(Session session) {
queue.add(session);
System.out.println("New session opened: "+session.getId());
}
@OnError
public void error(Session session, Throwable t) {
queue.remove(session);
System.err.println("Error on session "+session.getId());
}
@OnClose
public void closedConnection(Session session) {
queue.remove(session);
System.out.println("session closed: "+session.getId());
}
}