简体   繁体   English

Java Websocket与服务器的每个客户端连接创建新实例

[英]Java websocket creates new Instance with each client connection with server

I am using Java to create WebSocket Server And Javascript and HTML for the Client. 我正在使用Java为客户端创建WebSocket服务器以及Javascript和HTML。 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. 服务器成功启动,并且可以接受来自WebSocket客户端的连接,但是每次客户端连接时,它都在创建服务器的新实例。

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 . 在第二个客户端连接之后,它仅将1显示为一个计数,并且Set上仅存储一个会话。

Technologies I am using:- 我正在使用的技术:-

  1. Tomcat v9.0 Tomcat v9.0
  2. Eclipse Java EE IDE Eclipse Java EE IDE
  3. Java For Server And JavaScript For Client 服务器用Java和客户端用JavaScript
  4. javax.websocket for WebSocket. 用于WebSocket的javax.websocket。

My question is how can we stop this and make clients connect to only one instance? 我的问题是我们如何才能停止这种情况并使客户端仅连接到一个实例?

Look at the method names of WsServer. 查看WsServer的方法名称。 It is only intended for one client because the functions don't send a connection id with them. 它仅适用于一个客户端,因为函数不会与它们发送连接ID。 So make your counter static or move it to an other class. 因此,请将您的计数器设为static或将其移至其他类。

that is the default behaviour. 这是默认行为。

Try adding @Singleton annotation before @ServerEndpoint . 尝试添加@Singleton之前注释@ServerEndpoint

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM