2021-08-05
This commit is contained in:
15
web-socket-servlet/build.gradle.kts
Normal file
15
web-socket-servlet/build.gradle.kts
Normal file
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* Examples for Java
|
||||
*
|
||||
* Copyright (c) 2021. Elex. All Rights Reserved.
|
||||
* https://www.elex-project.com/
|
||||
*/
|
||||
|
||||
plugins {
|
||||
id("elex-war")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
providedCompile ("javax.servlet:javax.servlet-api:4.0.1")
|
||||
implementation("javax.websocket:javax.websocket-api:1.1")
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Examples for Java
|
||||
*
|
||||
* Copyright (c) 2021. Elex. All Rights Reserved.
|
||||
* https://www.elex-project.com/
|
||||
*/
|
||||
|
||||
package kr.pe.elex.examples;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import javax.websocket.*;
|
||||
import javax.websocket.server.ServerEndpoint;
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@ServerEndpoint("/")
|
||||
public class WebSocketServlet {
|
||||
private static final Set<Session> sessions;
|
||||
|
||||
static {
|
||||
sessions = new HashSet<>();
|
||||
}
|
||||
|
||||
@OnOpen
|
||||
public void onOpen(@NotNull Session session) throws IOException {
|
||||
sessions.add(session);//session.
|
||||
session.getBasicRemote().sendText("Hello");
|
||||
session.getUserProperties().put("createdOn", LocalDateTime.now());
|
||||
}
|
||||
|
||||
@OnClose
|
||||
public void onClose(Session session) {
|
||||
sessions.remove(session);
|
||||
session = null;
|
||||
}
|
||||
|
||||
@OnMessage
|
||||
public void onMessage(@NotNull Session session, String message) throws IOException {
|
||||
session.getBasicRemote().sendText("you said, " + message);
|
||||
}
|
||||
|
||||
@OnError
|
||||
public void onError(Session session, Throwable e) {
|
||||
|
||||
}
|
||||
|
||||
public static void broadcast(final String message){
|
||||
sessions.forEach(session -> {
|
||||
if (null!=session && session.isOpen()) {
|
||||
session.getAsyncRemote().sendText(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
* Examples for Java
|
||||
*
|
||||
* Copyright (c) 2021. Elex. All Rights Reserved.
|
||||
* https://www.elex-project.com/
|
||||
*/
|
||||
|
||||
package kr.pe.elex.examples;
|
||||
Reference in New Issue
Block a user