Java websocket creates new Instance with each client connection with server

1.6k views Asked by At

I am using Java to create WebSocket Server And Javascript and HTML for the Client. The server starts successfully and can accept connection from WebSocket clients, But it is creating a new instance of the server every time a client connects.

Code of Server:-

import java.util.HashSet;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;



@ServerEndpoint("/websocketendpoint")
public class WsServer {
    Set<Session> sessions = new HashSet<Session>(); 
    int count = 0;

    @OnOpen
    public void onOpen(Session session){
        System.out.println("Open Connection ...");
        count+=1; 
        System.out.println(count); //On the logcat it shows only 1
        sessions.add(session);

        for(Session s: sessions)
        {
            System.out.println(s); //On the logcat it shows only session
        }
    }

    @OnClose
    public void onClose(){
        System.out.println("Close Connection ...");
    }

    @OnMessage
    public String onMessage(String message){
        System.out.println("Message from the client: " + message);
        String echoMsg = "Echo from the server : " + message;
        return echoMsg;
    }

    @OnError
    public void onError(Throwable e){
        e.printStackTrace();
    }

}

Code Of Client:-

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tomcat WebSocket</title>
</head>
<body>
    <form>
        <input id="message" type="text">
        <input onclick="wsSendMessage();" value="Echo" type="button">
        <input onclick="wsCloseConnection();" value="Disconnect" type="button">
    </form>
    <br>
    <textarea id="echoText" rows="5" cols="30"></textarea>
    <script type="text/javascript">
        var webSocket = new WebSocket("ws://192.168.225.26:8080/WebSocketServerExample/websocketendpoint");
        var echoText = document.getElementById("echoText");
        echoText.value = "";
        var message = document.getElementById("message");
        webSocket.onopen = function(message){ wsOpen(message);};
        webSocket.onmessage = function(message){ wsGetMessage(message);};
        webSocket.onclose = function(message){ wsClose(message);};
        webSocket.onerror = function(message){ wsError(message);};
        function wsOpen(message){
            echoText.value += "Connected ... \n";
        }
        function wsSendMessage(){
            webSocket.send(message.value);
            echoText.value += "Message sended to the server : " + message.value + "\n";
            message.value = "";
        }
        function wsCloseConnection(){
            webSocket.close();
        }
        function wsGetMessage(message){
            echoText.value += "Message received from to the server : " + message.data + "\n";
        }
        function wsClose(message){
            echoText.value += "Disconnect ... \n";
        }

        function wserror(message){
            echoText.value += "Error ... \n";
        }
    </script>
</body>
</html>

And after the 2nd client connects it only shows 1 as a count and there is only one session is stored on the Set.

Technologies I am using:-

  1. Tomcat v9.0
  2. Eclipse Java EE IDE
  3. Java For Server And JavaScript For Client
  4. javax.websocket for WebSocket.

My question is how can we stop this and make clients connect to only one instance?

2

There are 2 answers

2
AudioBubble On BEST ANSWER

Look at the method names of WsServer. It is only intended for one client because the functions don't send a connection id with them. So make your counter static or move it to an other class.

0
gagan singh On

that is the default behaviour.

Try adding @Singleton annotation before @ServerEndpoint.