public class Server {
public static final ConcurrentHashMap<UUID, SocketIOClient> clients = new ConcurrentHashMap<UUID, SocketIOClient>();
public static final CountDownLatch latch = new CountDownLatch(1);
public void run() throws Exception {
Configuration configuration = new Configuration();
configuration.setHostname("127.0.0.1");//设置主机名
configuration.setPort(12121);//设置监听的端口号
SocketIOServer server = new SocketIOServer(configuration);//根据配置创建服务器对象
server.addConnectListener(new ConnectListener() {//添加客户端连接监听器
@Override
public void onConnect(SocketIOClient client) {
System.out.println("connected:SessionId=" + client.getSessionId());
clients.put(client.getSessionId(), client);//保存客户端
}
});
server.start();
System.out.println("server started");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Random random = new Random();
;//每隔一秒推送一次
clients.forEach((sessionId, client) -> {
client.sendEvent("pushpoint", new Point(random.nextInt(100), random.nextInt(100)));
}
);
}
}, 1000, 1000);
latch.await();
}
}