본문 바로가기

jsp

실시간 알림: 실시간으로 알림을 표시하는 예제.

반응형

실시간 알림은 사용자에게 중요한 사건, 업데이트 또는 기타 정보를 즉각적으로 알리기 위한 기능입니다. 이는 일반적으로 웹소켓, 서버-센트 이벤트(Server-Sent Events), 롱 폴링 등을 통해 구현됩니다. 사용자가 알림을 받으면 웹사이트나 애플리케이션에서 이를 적절한 방식으로 표시할 수 있습니다. 아래는 실시간 알림을 구현하는 두 가지 예제입니다.

예제 1: 웹소켓을 사용한 실시간 알림

이 예제에서는 웹소켓을 사용하여 서버에서 클라이언트로 실시간으로 알림을 보내는 방법을 구현합니다.

NotificationServlet.java

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/notifications")
public class NotificationServlet {
    private static final Set<Session> sessions = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
    }

    // 서버측에서 클라이언트로 알림을 보내는 메소드
    public static void sendNotification(String message) throws IOException {
        for (Session session : sessions) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(message);
            }
        }
    }
}

notificationClient.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Real-Time Notifications</title>
</head>
<body>
<script>
    var ws;

    function connect() {
        ws = new WebSocket("ws://localhost:8080/notifications");
        ws.onmessage = function(event) {
            var log = document.getElementById("notificationLog");
            log.innerHTML += event.data + "<br/>";
        };
    }

    window.onload = connect;
</script>
<div id="notificationLog">Notifications:</div>
</body>
</html>

예제 2: AJAX 롱 폴링을 사용한 실시간 알림

이 예제에서는 AJAX 롱 폴링을 사용하여 서버에서 클라이언트로 실시간으로 알림을 보내는 방법을 구현합니다.

longPolling.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Long Polling Notifications</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        function poll() {
            $.ajax({
                url: "serverNotification.jsp",
                success: function(data) {
                    var log = document.getElementById("notificationLog");
                    log.innerHTML += data + "<br/>";
                },
                complete: poll,
                timeout: 30000 // 30 seconds timeout
            });
        }

        $(document).ready(function(){
            poll(); // Start the polling process
        });
    </script>
</head>
<body>
<div id="notificationLog">Notifications:</div>
</body>
</html>

serverNotification.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // 이 파일은 서버에서 발생하는 이벤트를 기다리고,
    // 새로운 알림이 있을 때 클라이언트에게 정보를 반환합니다.
    // 예제를 단순화하기 위해 여기서는 Thread.sleep()을 사용하여
    // 대기하고 임의의 알림을 생성합니다.

    Thread.sleep(10000); // 10초 대기 (실제 애플리케이션에서는 이벤트 대기를 사용해야 합니다.)
    out.print("New notification at " + new java.util.Date()); // 임의의 알림 메시지
%>

반응형