我正在使用Java为客户端创建WebSocket服务器以及Javascript和HTML。服务器成功启动,可以接受来自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>
第二个客户端连接后,它只显示1作为计数,Set
上仅存储一个会话。
我正在使用的技术:-
我的问题是我们如何才能停止此过程并使客户端仅连接到一个实例?
答案 0 :(得分:0)
查看WsServer的方法名称。它仅适用于一个客户端,因为函数不会与它们发送连接ID。因此,将您的计数器static
或移至其他班级。
答案 1 :(得分:0)
这是默认行为。
尝试在@Singleton
之前添加@ServerEndpoint
注释。