我有一个小的Eclipse Jetty websockets示例程序,其中JavaScript客户端可以连接并断开与Java Server的连接,我想向所有连接的客户端发送一条简单的消息(广播消息)。
import java.io.IOException;
import java.util.ArrayList;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
public class WebSocketTest {
private static final WebSocketTest webSocketTestInstance = new WebSocketTest();
private static ArrayList<MyWebSocketHandler> clients = new ArrayList<>();
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
WebSocketHandler wsHandler = new WebSocketHandler() {
@Override
public void configure(WebSocketServletFactory factory) {
factory.register(MyWebSocketHandler.class);
}
};
server.setHandler(wsHandler);
server.start();
//this is for testing only
for(int i=0; i<10;i++){
try {
Thread.sleep(3000);
} catch(InterruptedException ex) {Thread.currentThread().interrupt();}
broadcast("Test Message!"+i);
}
server.join();
}
public static WebSocketTest getServer() {
return webSocketTestInstance;
}
public static void addClient(MyWebSocketHandler client) {
clients.add(client);
}
public static void broadcast(String msg){
for( MyWebSocketHandler client : clients ){
if ( client.session.isOpen() ){
try{
client.session.getRemote().sendString(msg);
} catch (IOException e) {}
}
}
}
}
@WebSocket
public class MyWebSocketHandler {
public Session session;
private WebSocketTest server = WebSocketTest.getServer();
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("Close: statusCode=" + statusCode + ", reason=" + reason);
}
@OnWebSocketError
public void onError(Throwable t) {
System.out.println("Error: " + t.getMessage());
}
@OnWebSocketConnect
public void onConnect(Session session) {
this.session = session;
this.server.addClient(this);
System.out.println("Connect: " + session.getRemoteAddress().getAddress());
try {
session.getRemote().sendString("Hello Webbrowser");
} catch (IOException e) {
e.printStackTrace();
}
}
@OnWebSocketMessage
public void onMessage(String message) {
System.out.println("Message: " + message);
}
// sends message to browser
public void send(String message) {
try {
if (session.isOpen()) {
session.getRemote().sendString(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
目前我在WebSocketTest
中获得MyWebSocketHandler
实例,然后我调用.addClient(this)
方法将客户端存储在客户端列表中,以便稍后我可以迭代客户端列表和向每个客户发送消息。虽然这有效,但我不喜欢这个解决方案。
我的问题是:jetty.Server
类是否有方法或任何方式轻松获取客户端会话?(如server.getAllSessions()或getAllClients())。我查看了Server
课程的文档,但我找不到任何内容。