如何在没有 javascript 实现的情况下部署 Jakarta WebSocket @ServerEndpoint 类

问题描述 投票:0回答:1

我已经在互联网上搜索过,但到目前为止,Jakarta 存储库的所有文档均不成功。实际上没有任何关于如何部署端点的内容。显然,除非部署,否则端点只是一个无用的文件。下面是 Websocket 服务器端点。

package com.wsserver;

import java.io.IOException;

import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;

@ServerEndpoint("/ws")
public class WebSocketEndpoint {

    @OnOpen
    public void onOpen(Session session) {

        System.out.println("WebSocket opened: " + session.getId());

    }

    @OnMessage
    public void onMessage(String message, Session session) {

        System.out.println("Message received: " + message);

        try {

            session.getBasicRemote().sendText("Echo: " + message);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {

        System.out.println("WebSocket closed: " + session.getId());

    }

    @OnError
    public void onError(Session session, Throwable throwable) {

        System.out.println("WebSocket error: " + session.getId());
        throwable.printStackTrace();

    }

}

这是main.java文件

package com.wsserver;

import jakarta.websocket.ContainerProvider;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;
import jakarta.websocket.server.ServerEndpoint;
import jakarta.websocket.server.ServerEndpointConfig;

import java.net.URI;
import java.net.http.WebSocket;

@ServerEndpoint("/ws")
public class Main {
    
    public static void main(String[] args) throws Exception {

        ServerEndpointConfig serverEndpoint = ServerEndpointConfig.Builder.create(WebsocketEndpoint.class, "/pathToRoot/").build();

    }

}

websocket 服务器 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wsserver</groupId>
    <artifactId>server</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.18.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.18.2</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.18.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/jakarta.websocket/jakarta.websocket-api -->
        <dependency>
            <groupId>jakarta.websocket</groupId>
            <artifactId>jakarta.websocket-api</artifactId>
            <version>2.2.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.11.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/jakarta.websocket/jakarta.websocket-client-api -->
        <dependency>
            <groupId>jakarta.websocket</groupId>
            <artifactId>jakarta.websocket-client-api</artifactId>
            <version>2.2.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.glassfish.tyrus.bundles/tyrus-standalone-client -->
        <dependency>
            <groupId>org.glassfish.tyrus.bundles</groupId>
            <artifactId>tyrus-standalone-client</artifactId>
            <version>2.2.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20241224</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>9.1.0</version>
        </dependency>

    </dependencies>

</project>

Main.java 似乎成功构建了 websocket,但是我如何监听事件?任何见解都会很棒。谢谢。

这是我用来将数据传递到 websocket 服务器的工作 websocket 客户端:

package com.wsclient;

import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;

import jakarta.websocket.ClientEndpoint;
import jakarta.websocket.CloseReason;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;

@ClientEndpoint
public class WebsocketClientEndpoint {

    Session userSession = null;
    private MessageHandler messageHandler;

    public WebsocketClientEndpoint(URI endpointURI) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(this, endpointURI);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @OnOpen
    public void onOpen(Session userSession) {
        System.out.println("opening websocket");
        this.userSession = userSession;
    }

    @OnClose
    public void onClose(Session userSession, CloseReason reason) {
        System.out.println("closing websocket");
        this.userSession = null;
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        if (this.messageHandler != null) {
            this.messageHandler.handleMessage(message);
        }
    }

    @OnMessage
    public void onMessage(ByteBuffer bytes) {
        System.out.println("Handle byte buffer");
    }
    
    public void addMessageHandler(MessageHandler msgHandler) {
        this.messageHandler = msgHandler;
    }

    public void sendMessage(String message) {
        this.userSession.getAsyncRemote().sendText(message);
    }

    public static interface MessageHandler {
        public void handleMessage(String message) throws IOException;
    }

}

这里是 Main.java,我在其中调用 websocket 客户端:

package com.wsclient;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

    public static void main(String[] args) throws Exception {
try {
            
            // open websocket
            final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("wss://somedomain.com/ws"));

            clientEndPoint.addMessageHandler(
                
                new WebsocketClientEndpoint.MessageHandler() {

                    public void handleMessage(String packet) {

                        System.out.println(packet);
                        
                    }

                }

            );

            clientEndPoint.sendMessage(payload);
            
            while (true) {
            
                Thread.sleep(1000);

            }

以及我的 websocket 客户端的 pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>rtw</groupId>
    <artifactId>rtw</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.18.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.18.2</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.18.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/jakarta.websocket/jakarta.websocket-api -->
        <dependency>
            <groupId>jakarta.websocket</groupId>
            <artifactId>jakarta.websocket-api</artifactId>
            <version>2.2.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.11.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/jakarta.websocket/jakarta.websocket-client-api -->
        <dependency>
            <groupId>jakarta.websocket</groupId>
            <artifactId>jakarta.websocket-client-api</artifactId>
            <version>2.2.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.glassfish.tyrus.bundles/tyrus-standalone-client -->
        <dependency>
            <groupId>org.glassfish.tyrus.bundles</groupId>
            <artifactId>tyrus-standalone-client</artifactId>
            <version>2.2.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20241224</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>9.1.0</version>
        </dependency>

    </dependencies>

</project>

我的目标是在 JAVA 中拥有一个 websocket 服务器,它也以与我的 websocket 客户端相同的方式在 Main.java 中调用。

jakarta-ee websocket
1个回答
0
投票

Jakarta EE 示例代码:

如果您正在寻找符合 Jakarta EE 的示例代码,请查看以下位置:

Jakarta EE 教程示例

https://jakarta.ee/learn/docs/jakartaee-tutorial/current/intro/usingexamples/usingexamples.html

教程示例代码位于 https://github.com/eclipse-ee4j/jakartaee-examples

野蝇

https://www.wildfly.org/downloads/

34.0.1.Final 或 35.0.0.Final ,找到 快速入门源代码 -> zip https://github.com/wildfly/quickstart/releases/download/35.0.0.Final/wildfly- 35.0.0.Final-quickstarts.zip

WebSocket 示例:

项目树

有关其他示例,请参阅 GlassFish 示例: https://github.com/eclipse-ee4j/glassfish-samples/tree/master/ws/jakartaee9

此示例项目是从以下项目修改而来的:

https://github.com/eclipse-ee4j/glassfish-samples/tree/master/ws/jakartaee9/websocket/echo

jakartaee10-websocket-echo
├── pom.xml
└── src
    └── main
        ├── java
        │   └── org
        │       └── glassfish
        │           └── samples
        │               └── websocket
        │                   └── echo
        │                       └── EchoEndpoint.java
        └── webapp
            ├── index.html
            └── WEB-INF
                └── glassfish-web.xml

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.glassfish-samples</groupId>
    <version>6.0-SNAPSHOT</version>
    <artifactId>websocket-samples-echo</artifactId>
    <packaging>war</packaging>

    <name>WebSocket Echo Sample Application</name>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>jakarta.platform</groupId>
            <artifactId>jakarta.jakartaee-api</artifactId>
            <version>10.0.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
    <build>
        <finalName>websocket-echo</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <warName>websocket-echo</warName>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

EchoEndpoint.java

将代码复制到此类中。

package org.glassfish.samples.websocket.echo;

import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;

import java.io.IOException;

/**
 * Echo endpoint.
 */
@ServerEndpoint("/echo")
public class EchoEndpoint {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocket opened: " + session.getId());
    }

    /**
     * Incoming message is represented as parameter and return value is going to be send back to peer.
     * </p>
     * {@link jakarta.websocket.Session} can be put as a parameter and then you can gain better control of whole
     * communication, like sending more than one message, process path parameters, {@link jakarta.websocket.Extension Extensions}
     * and sub-protocols and much more.
     *
     * @param message incoming text message.
     * @return outgoing message.
     * @see OnMessage
     * @see jakarta.websocket.Session
     */
    /*
    @OnMessage
    public String echo(String message) {
        return message;
    }
    */
    @OnMessage
    public void onMessage(String message, Session session) {

        System.out.println("Message received: " + message);
        try {
            session.getBasicRemote().sendText("Echo: " + message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("WebSocket closed: " + session.getId());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("WebSocket error: " + session.getId());
        throwable.printStackTrace();
    }
}

index.html

https://github.com/eclipse-ee4j/glassfish-samples/blob/master/ws/jakartaee9/websocket/echo/src/main/webapp/index.html

glassfish-web.xml

https://github.com/eclipse-ee4j/glassfish-samples/blob/master/ws/jakartaee9/websocket/echo/src/main/webapp/WEB-INF/glassfish-web.xml

构建

mvn clean package

输出文件:

websocket-echo.war

jakartaee10-websocket-echo/target/websocket-echo.war

部署战争文件

websocket-echo.war
放入
apache-tomcat-10.1.24/webapps

启动Tomcat

在Tomcat目录下

cd bin
./startup.sh

测试

火狐打开:

http://localhost:8080/websocket-echo/

输入一些字符串

enter image description here

关闭火狐浏览器

检查日志文件

apache-tomcat-10.1.24/logs/catalina.out

您的代码

System.out.println
输出到catalina.out

WebSocket opened: 0
Message received: Hello World - WebSocket!
WebSocket opened: 1
Message received: Hello 1
WebSocket opened: 2
Message received: Hello 2
WebSocket closed: 0
WebSocket closed: 1
WebSocket closed: 2

如何连接到WebSocket

在此示例中,您的 Web 应用程序的网页位于

src/main/webapp/index.html

index.html
文件使用 JavaScript 连接到您的 WebSocket。

<script language="javascript" type="text/javascript">
    var wsUri = getRootUri() + "/websocket-echo/echo";
...
© www.soinside.com 2019 - 2024. All rights reserved.