Getting started with WebSockets Next
本指南说明了你的 Quarkus 应用程序如何利用 Web 套接字创建交互式 Web 应用程序。在本指南中,我们将使用 Web 套接字开发一个非常简单的聊天应用程序,以便接收和向其他已连接用户发送消息。
This guide explains how your Quarkus application can utilize web sockets to create interactive web applications. In this guide, we will develop a very simple chat application using web sockets to receive and send messages to the other connected users. Unresolved directive in websockets-next-tutorial.adoc - include::{includes}/extension-status.adoc[]
Prerequisites
Unresolved directive in websockets-next-tutorial.adoc - include::{includes}/prerequisites.adoc[]
Quarkus WebSockets vs. Quarkus WebSockets Next
本指南使用 quarkus-websockets-next
扩展。此扩展是 WebSocket API 的新实现,比原始 quarkus-websockets
扩展更高效、更易用。原始 quarkus-websockets
扩展仍然可用,并将继续受到支持。
This guide uses the quarkus-websockets-next
extension.
This extension is a new implementation of the WebSocket API that is more efficient and easier to use than the original quarkus-websockets
extension. The original quarkus-websockets
extension is still available and will continue to be supported.
与 quarkus-websockets
不同, quarkus-web-socket-next
不实现 Jakarta WebSocket 。相反,它提供了一个简化且更现代化的 API,更易于使用。同时,它还被设计为可与 Quarkus 的响应式编程模型和 Quarkus 的网络层高效配合使用。
Unlike quarkus-websockets
, quarkus-web-socket-next
does NOT implement Jakarta WebSocket.
Instead, it provides a simplified and more modern API that is easier to use.
It is also designed to work efficiently with Quarkus' reactive programming model and the Quarkus' networking layer.
What you’ll learn
-
How to use the
quarkus-websockets-next
extension -
How to declare a web socket endpoint
-
How to send and receive messages using web sockets
-
How to broadcast messages to all connected users
-
How to be notified of new connections and disconnections
-
How to use path parameters in web socket URLs
Architecture
在本指南中,我们创建一个简单的聊天应用程序,使用 Web 套接字接收和向其他已连接用户发送消息。
In this guide, we create a straightforward chat application using web sockets to receive and send messages to the other connected users.
Solution
我们建议你按照后续章节中的说明,逐步创建应用程序。但是,你可以直接跳到已完成的示例。
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can skip right to the completed example.
克隆 Git 存储库: git clone {quickstarts-clone-url}
,或下载 {quickstarts-archive-url}[存档]。
Clone the Git repository: git clone {quickstarts-clone-url}
, or download an {quickstarts-archive-url}[archive].
解决方案位于 websockets-next-quickstart
directory 。
The solution is located in the websockets-next-quickstart
directory.
Creating the Maven project
首先,我们需要一个新项目。使用以下命令创建一个新项目:
First, we need a new project. Create a new project with the following command:
Unresolved directive in websockets-next-tutorial.adoc - include::{includes}/devtools/create-app.adoc[]
该命令生成项目(不含任何类)并导入`websockets-next`扩展。
This command generates the project (without any classes) and imports the websockets-next
extension.
如果您已经配置了 Quarkus 项目,可以通过在项目基本目录中运行以下命令将 `websockets-next`扩展添加到项目:
If you already have your Quarkus project configured, you can add the websockets-next
extension
to your project by running the following command in your project base directory:
Unresolved directive in websockets-next-tutorial.adoc - include::{includes}/devtools/extension-add.adoc[]
这会将以下内容添加到构建文件中:
This will add the following to your build file:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-websockets-next</artifactId>
</dependency>
implementation("io.quarkus:quarkus-websockets-next")
Declaring a WebSocket endpoint
我们的应用程序包含处理 WebSocket 的单个类。在`src/main/java`目录中创建class org.acme.websockets.ChatWebSocket
。将以下内容复制到创建的文件中:
Our application contains a single class that handles the web sockets.
Create the org.acme.websockets.ChatWebSocket
class in the src/main/java
directory.
Copy the following content into the created file:
package org.acme.websockets;
import io.quarkus.websockets.next.OnClose;
import io.quarkus.websockets.next.OnOpen;
import io.quarkus.websockets.next.OnTextMessage;
import io.quarkus.websockets.next.WebSocket;
import io.quarkus.websockets.next.WebSocketConnection;
import jakarta.inject.Inject;
@WebSocket(path = "/chat/{username}") (1)
public class ChatWebSocket {
// Declare the type of messages that can be sent and received
public enum MessageType {USER_JOINED, USER_LEFT, CHAT_MESSAGE}
public record ChatMessage(MessageType type, String from, String message) {
}
@Inject
WebSocketConnection connection; (2)
@OnOpen(broadcast = true) (3)
public ChatMessage onOpen() {
return new ChatMessage(MessageType.USER_JOINED, connection.pathParam("username"), null);
}
@OnClose (4)
public void onClose() {
ChatMessage departure = new ChatMessage(MessageType.USER_LEFT, connection.pathParam("username"), null);
connection.broadcast().sendTextAndAwait(departure);
}
@OnTextMessage(broadcast = true) (5)
public ChatMessage onMessage(ChatMessage message) {
return message;
}
}
1 | Declares the web socket endpoint and configure the path. Note that the path can contain a path parameter: username . |
2 | A session scoped bean that represents the connection to the client. It allows sending messages programmatically and retrieve the path parameters. |
3 | This method is called when a new client connects. The broadcast = true attribute indicates that the returned message should be sent to all connected clients. |
4 | This method is called when a client disconnects. The method uses the WebSocketConnection to broadcast a message to all remaining connected clients. |
5 | This method is called when a client sends a message. The broadcast = true attribute indicates that the returned message should be sent to all connected clients. Here, we just returns the received (text) message. |
正如您所见,Quarkus 使用注释处理 WebSocket 生命周期和消息处理。它还使用 JSON 自动序列化和反序列化消息。
As you can see, Quarkus handles the web socket lifecycle and message handling using annotations. It also serializes and deserializes messages using JSON automatically.
A slick web frontend
所有聊天应用程序都需要一个 _nice_UI,嗯,这个可能不太好,但却能完成工作。Quarkus 会自动提供 `META-INF/resources`目录中包含的静态资源。创建 `src/main/resources/META-INF/resources`目录并将此 index.html文件复制到其中。
All chat applications need a nice UI, well, this one may not be that nice, but does the work.
Quarkus automatically serves static resources contained in the META-INF/resources
directory.
Create the src/main/resources/META-INF/resources
directory and copy this index.html file in it.
Run the application
现在,让我们看看应用程序在实际应用中的情况。使用以下命令运行它:
Now, let’s see our application in action. Run it with:
Unresolved directive in websockets-next-tutorial.adoc - include::{includes}/devtools/dev.adoc[]
然后在 2 个浏览器窗口中打开 [role="bare"][role="bare"]http://localhost:8080/:
Then open your 2 browser windows to [role="bare"]http://localhost:8080/:
-
Enter a name in the top text area (use 2 different names).
-
Click on connect
-
Send and receive messages
和往常一样,可以使用以下命令打包应用程序:
As usual, the application can be packaged using:
Unresolved directive in websockets-next-tutorial.adoc - include::{includes}/devtools/build.adoc[]
并使用 `java -jar target/quarkus-app/quarkus-run.jar`执行。
And executed using java -jar target/quarkus-app/quarkus-run.jar
.
您还可以使用以下命令构建本机可执行文件:
You can also build the native executable using:
Unresolved directive in websockets-next-tutorial.adoc - include::{includes}/devtools/build-native.adoc[]
Conclusion
这篇简短的入门指南向您展示了如何使用 `quarkus-websockets-next`扩展创建一个简单的聊天应用程序。在 dedicated reference guide上了解有关此扩展的更多信息。
This short getting started guide has shown you how to create a simple chat application using the quarkus-websockets-next
extension.
Learn more about this extension on the dedicated reference guide.