>  기사  >  Java  >  Java Websocket은 온라인 드로잉 보드 기능을 어떻게 구현합니까?

Java Websocket은 온라인 드로잉 보드 기능을 어떻게 구현합니까?

WBOY
WBOY원래의
2023-12-02 13:41:35709검색

Java Websocket如何实现在线画板功能?

Java Websocket은 온라인 드로잉 보드 기능을 어떻게 구현하나요?

Websocket은 HTML5에서 권장하는 새로운 프로토콜로, 이를 통해 클라이언트와 서버가 서로 메시지를 보내고 실시간 통신을 할 수 있습니다. 이 프로토콜을 사용하면 온라인 드로잉 보드 기능을 더욱 안정적이고 안전하며 실시간으로 만들 수 있습니다. 다음 글에서는 Java Websocket을 사용하여 온라인 드로잉 보드 기능을 구현하는 방법을 소개하고, 모두의 이해를 돕기 위해 몇 가지 샘플 코드를 첨부하겠습니다.

먼저 Websocket 프로토콜을 빠르고 간단하게 구현하는 데 도움이 되는 Java Websocket 프레임워크를 사용해야 합니다. 다음은 Java Websocket을 사용한 메시지 브로드캐스트용 샘플 코드입니다.

@ServerEndpoint("/broadcast")
public class Broadcaster {
    static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

    @OnMessage
    public void onMessage(String message, Session session) throws IOException, EncodeException {
        synchronized (sessions) {
            for (Session s : sessions) {
                if (!s.equals(session)) {
                    s.getBasicRemote().sendText(message);
                }
            }
        }
    }

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

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

이 샘플 코드에서는 "/broadcast" 주석이 달린 Websocket 엔드포인트를 생성합니다. 새로운 연결이 있을 때마다 Websocket 서버는 onOpen() 메서드를 호출합니다. 이 메서드는 컬렉션에 클라이언트 연결을 추가합니다. 클라이언트가 메시지를 보낼 때마다 Websocket 서버는 onMessage() 메서드를 호출합니다. onMessage() 메서드는 연결된 모든 클라이언트를 반복한 다음 메시지 보낸 사람을 제외한 모든 클라이언트에 메시지를 보냅니다. 클라이언트 연결이 끊어질 때마다 Websocket 서버는 연결된 컬렉션에서 연결을 제거하는 onClose() 메서드를 호출합니다.

다음으로 프런트 엔드 JavaScript로 제어되는 캔버스 구성 요소를 정의하고 아트보드를 관리하는 Java 개체를 Websocket에 연결해야 합니다.

window.onload = function() {
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var drawing = false;
    var lastX, lastY;

    var socket = new WebSocket('<websocket_url>');

    socket.onopen = function() {
        console.log('Connection opened');
    };

    socket.onmessage = function(message) {
        console.log('Message received: ' + message.data);
        var data = JSON.parse(message.data);
        drawLine(data.x1, data.y1, data.x2, data.y2, data.color);
    };

    socket.onerror = function() {
        console.log('Error');
    };

    socket.onclose = function() {
        console.log('Connection closed');
    };

    function startDrawing(event) {
        drawing = true;
        lastX = event.pageX - canvas.offsetLeft;
        lastY = event.pageY - canvas.offsetTop;
    }

    function stopDrawing() {
        drawing = false;
        socket.send(JSON.stringify({ eventType: 'stopDrawing' }));
    }

    function onDrawing(event) {
        if (!drawing) return;
        var currentX = event.pageX - canvas.offsetLeft;
        var currentY = event.pageY - canvas.offsetTop;
        drawLine(lastX, lastY, currentX, currentY, '#000');
        socket.send(JSON.stringify({ eventType: 'drawing', x1: lastX, y1: lastY, x2: currentX, y2: currentY, color: '#000' }));
        lastX = currentX;
        lastY = currentY;
    }

    function drawLine(x1, y1, x2, y2, color) {
        context.beginPath();
        context.moveTo(x1, y1);
        context.lineTo(x2, y2);
        context.strokeStyle = color;
        context.stroke();
    }

    canvas.addEventListener('mousedown', startDrawing);
    canvas.addEventListener('mouseup', stopDrawing);
    canvas.addEventListener('mousemove', onDrawing);
};

이 샘플 코드에서는 WebSocket 개체를 사용하여 onopen을 설정합니다. onmessage, onerror 및 onclose 이벤트는 클라이언트 JavaScript 코드와 WebSocket 서버 간의 연결 및 데이터 처리를 처리합니다. 마우스를 누르면 클라이언트 코드는 start드로잉() 함수를 호출하여 후속 마우스 움직임의 궤적을 캔버스에 그리고 소켓.send() 메서드를 호출하여 명령을 Websocket 서버에 보냅니다. 클라이언트가 보낸 명령을 받은 후 서버는 이 명령을 연결된 모든 클라이언트에 전달합니다. 마우스를 놓으면 클라이언트 코드는 stop드로잉() 함수를 호출합니다. 이 함수는 그리기 프로세스가 중지되었음을 서버에 알립니다.

마지막으로 서버에 Websocket을 구성해야 합니다. 다음은 일부 Websocket 구성 샘플 코드입니다.

<dependencies>
    <dependency>
        <groupId>javax.websocket</groupId>
        <artifactId>javax.websocket-api</artifactId>
        <version>1.1</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.tyrus.bundles</groupId>
        <artifactId>tyrus-standalone-server</artifactId>
        <version>1.13.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <webResources>
                    <resource>
                        <directory>src/main/webapp</directory>
                    </resource>
                </webResources>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.6.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                    <phase>install</phase>
                    <configuration>
                        <mainClass>org.glassfish.tyrus.standalone.Server</mainClass>
                        <arguments>
                            <argument>--host</argument>
                            <argument>localhost</argument>
                            <argument>--port</argument>
                            <argument>8090</argument>
                            <argument>--contextPath</argument>
                            <argument>/</argument>
                            <argument>--appBase</argument>
                            <argument>./src/main/webapp</argument>
                            <argument>--monitoring</argument>
                        </arguments>
                        <classpathScope>compile</classpathScope>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>repo.maven.apache.org</id>
        <url>https://repo.maven.apache.org/maven2</url>
    </repository>
</repositories>

<profiles>
    <profile>
        <id>launch</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>
                    <version>1.6.0</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>java</goal>
                            </goals>
                            <phase>install</phase>
                            <configuration>
                                <mainClass>com.test.websocket.Broadcaster</mainClass>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

이 샘플 코드에서는 Maven을 사용하여 Java 웹 애플리케이션을 컴파일, 빌드 및 배포하고 tyrus-standalone-server 모듈을 사용하여 WebSocket 프로토콜에 대한 지원을 제공합니다.

온라인 드로잉보드 기능을 쉽게 구현하기 위해 위의 코드를 사용합니다. 이 기능은 의사가 환자의 상태를 더 잘 분석하고 교육자가 학생과 답변을 공유하는 등 다양한 상황에서 사용할 수 있습니다. Websocket을 기반으로 한 온라인 드로잉 보드 기능은 이러한 상황을 더욱 편리하고 효율적으로 만들어줍니다.

위 내용은 Java Websocket은 온라인 드로잉 보드 기능을 어떻게 구현합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.