我的IDE:NetBeans,GlassFish。 我试图了解GlassFish如何执行和运行端点! 我理解Glassfish作为Web服务器为每个连接创建新的Endpoint实例,代码中的Set:peers作为每个端点实例的一个全局变量。 我的问题是:如何添加另一个全局变量,以便每个端点实例都可以访问它?
enter code here
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/echo")
public class EchoServer {
/**
* @OnOpen allows us to intercept the creation of a new session.
* The session class allows us to send data to the user.
* In the method onOpen, we'll let the user know that the handshake was
* successful.
*/
private static final Set<Session > peers = Collections.synchronizedSet(new HashSet<Session >());
@OnOpen
public void onOpen(Session session){
System.out.println(session.getId() + " has opened a connection");
try {
peers.add(session);
session.getBasicRemote().sendText("Connection Established");
} catch (IOException ex) {
ex.printStackTrace();
}
}
@OnMessage
public void onMessage(String message, Session session) throws IOException{
System.out.println("Message from " + session.getId() + ": " + message);
for (Session peer : peers) {
peer.aplayer.getBasicRemote().sendText(" Message from " + session.getId()+" : "+message);
}
}`enter code here`
@OnClose
public void onClose(Session session){
System.out.println("Session " +session.getId()+" has ended");
peers.remove(session);
}
}