본문 바로가기

jsp

웹 소켓 통신: 웹 소켓을 사용하여 실시간 통신을 구현하는 예제.

반응형

웹 소켓은 실시간 양방향 통신을 위한 기술로, 클라이언트와 서버 간에 지속적인 연결을 유지합니다. 웹 소켓을 사용하면 서버와 클라이언트가 메시지를 즉시 교환할 수 있으며, 이는 채팅 애플리케이션, 실시간 게임, 라이브 스트리밍 등에 사용됩니다. JSP만으로 웹 소켓을 직접 구현하기는 어렵지만, Java API for WebSocket(Jakarta EE)과 같은 기술을 사용하여 구현할 수 있습니다. 아래는 웹 소켓을 사용하여 실시간 통신을 구현하는 예제입니다.

예제 1: 간단한 웹 소켓 서버 및 클라이언트 구현

이 예제에서는 웹 소켓을 사용하여 서버와 클라이언트 간에 간단한 메시지를 주고받는 예제를 보여줍니다. Java EE의 @ServerEndpoint를 사용하여 웹 소켓 서버를 구현합니다.

MyWebSocketServer.java

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket")
public class MyWebSocketServer {

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Open connection " + session.getId());
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("Close connection " + session.getId());
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        return "Server received [" + session.getId() + "]: " + message;
    }

    @OnError
    public void onError(Throwable t) {
        t.printStackTrace();
    }
}

index.html

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Test</title>
    <script type="text/javascript">
        var ws;
        function connect() {
            ws = new WebSocket("ws://localhost:8080/websocket");
            ws.onmessage = function(event) {
                var log = document.getElementById("log");
                log.innerHTML += event.data + "\n";
            };
        }

        function send() {
            var input = document.getElementById("input");
            ws.send(input.value);
            input.value = '';
        }
    </script>
</head>
<body onload="connect();">
    <h2>WebSocket Test</h2>
    <input type="text" id="input" value="Hello, World!">
    <button onclick="send();">Send</button>
    <pre id="log"></pre>
</body>
</html>

chatClient.html

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Chat Client</title>
    <script type="text/javascript">
        var ws;
        function connect() {
            var username = document.getElementById("username").value;
            ws = new WebSocket("ws://localhost:8080/chat/" + username);
            
            ws.onopen = function() {
                updateStatus("Connected");
            };
            
            ws.onmessage = function(event) {
                var log = document.getElementById("chatlog");
                log.innerHTML += event.data + "\n";
            };
            
            ws.onclose = function() {
                updateStatus("Disconnected");
            };
        }
        
        function send() {
            var content = document.getElementById("msg").value;
            ws.send(content);
            document.getElementById("msg").value = '';
        }

        function updateStatus(status) {
            document.getElementById("status").innerHTML = status;
        }
    </script>
</head>
<body>
    <h2>WebSocket Chat Client</h2>
    Username: <input type="text" id="username" value="Guest"/><br>
    <button onclick="connect();">Connect</button>
    <div id="status">Disconnected</div>
    <textarea id="chatlog" rows="20" cols="50"></textarea><br>
    <input type="text" id="msg">
    <button onclick="send();">Send</button>
</body>
</html>

 

반응형