Home  >  Article  >  Java  >  How to implement a graphical interface for real-time communication using JavaFX and WebSocket in Java 9

How to implement a graphical interface for real-time communication using JavaFX and WebSocket in Java 9

WBOY
WBOYOriginal
2023-07-30 16:57:23950browse

How to use JavaFX and WebSocket to implement a graphical interface for real-time communication in Java 9

Introduction:
With the development of the Internet, the need for real-time communication is becoming more and more common. In Java 9, we can use JavaFX and WebSocket technologies to implement real-time communication applications with graphical interfaces. This article will introduce how to use JavaFX and WebSocket technology to implement a graphical interface for real-time communication in Java 9, and attach corresponding code examples.

Part One: JavaFX Basics
Before we start to introduce how to use WebSocket to achieve real-time communication, let's first understand the basic knowledge of JavaFX. JavaFX is a framework launched by Oracle for developing graphical interfaces. It uses an XML-based description language FXML to define the interface layout.

Code Example 1:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;

public class JavaFXExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button("点击我");
        btn.setOnAction(e -> {
            System.out.println("Hello JavaFX");
        });

        Scene scene = new Scene(btn, 300, 200);

        primaryStage.setTitle("JavaFX示例");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

In the above code, we created a simple JavaFX application window and added a button to the window. When the button is clicked, "Hello JavaFX" will be output to the console.

Part 2: WebSocket Basics
WebSocket is a protocol used to achieve real-time communication, which provides two-way communication functionality. In Java, we can use the WebSocket class in the Java API to implement WebSocket communication.

Code Example 2:

import java.net.URI;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;

public class WebSocketExample {

    public static void main(String[] args) {
        String serverURL = "ws://example.com/websocket";

        CompletableFuture<WebSocket> ws = WebSocket.newWebSocketBuilder()
                .buildAsync(URI.create(serverURL), new WebSocket.Listener() {
                    @Override
                    public void onOpen(WebSocket webSocket) {
                        System.out.println("连接已建立");
                    }

                    @Override
                    public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
                        System.out.println("接收到消息:" + data.toString());
                        return WebSocket.Listener.super.onText(webSocket, data, last);
                    }

                    @Override
                    public CompletionStage<?> onBinary(WebSocket webSocket, ByteBuffer data, boolean last) {
                        System.out.println("接收到二进制数据");
                        return WebSocket.Listener.super.onBinary(webSocket, data, last);
                    }

                    @Override
                    public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
                        System.out.println("连接已关闭,状态码:" + statusCode);
                        return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
                    }

                    @Override
                    public void onError(WebSocket webSocket, Throwable error) {
                        System.out.println("发生错误:" + error.getMessage());
                    }
                });

        // 向服务器发送消息
        ws.thenAccept(webSocket -> {
            webSocket.sendText("Hello Server", true);
        });

        // 断开连接
        ws.thenAccept(WebSocket::abort);
    }
}

In the above code, we create a WebSocket and connect to the specified server. Through the callback method of WebSocket, we can handle the interaction with the server, including receiving and sending messages, and handling the connection status.

Part 3: Using JavaFX and WebSocket to implement a graphical interface for real-time communication
Now that we have understood the basics of JavaFX and WebSocket, we will combine these two technologies to implement a graphical interface real-time communication applications.

Code Example 3:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.net.URI;
import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;

public class RealTimeCommunicationApp extends Application {
    private WebSocket webSocket;
    private TextArea messageArea;

    @Override
    public void start(Stage primaryStage) {
        VBox root = new VBox();
        messageArea = new TextArea();
        TextField inputField = new TextField();

        inputField.setOnAction(e -> {
            String message = inputField.getText();
            webSocket.sendText(message, true);
            inputField.clear();
        });

        root.getChildren().addAll(messageArea, inputField);

        Scene scene = new Scene(root, 400, 300);
        primaryStage.setTitle("实时通信应用");
        primaryStage.setScene(scene);
        primaryStage.show();

        connectToServer();
    }

    private void connectToServer() {
        String serverURL = "ws://example.com/websocket";

        CompletableFuture<WebSocket> ws = WebSocket.newWebSocketBuilder()
                .buildAsync(URI.create(serverURL), new WebSocket.Listener() {
                    @Override
                    public void onOpen(WebSocket webSocket) {
                        Platform.runLater(() -> {
                            messageArea.appendText("连接已建立
");
                        });
                    }

                    @Override
                    public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
                        Platform.runLater(() -> {
                            messageArea.appendText("接收到消息:" + data.toString() + "
");
                        });
                        return WebSocket.Listener.super.onText(webSocket, data, last);
                    }

                    @Override
                    public CompletionStage<?> onBinary(WebSocket webSocket, ByteBuffer data, boolean last) {
                        Platform.runLater(() -> {
                            messageArea.appendText("接收到二进制数据
");
                        });
                        return WebSocket.Listener.super.onBinary(webSocket, data, last);
                    }

                    @Override
                    public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
                        Platform.runLater(() -> {
                            messageArea.appendText("连接已关闭,状态码:" + statusCode + "
");
                        });
                        return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);
                    }

                    @Override
                    public void onError(WebSocket webSocket, Throwable error) {
                        Platform.runLater(() -> {
                            messageArea.appendText("发生错误:" + error.getMessage() + "
");
                        });
                    }
                });

        ws.thenAccept(webSocket -> {
            this.webSocket = webSocket;
        });
    }

    public static void main(String[] args) {
        launch(args);
    }
}

In the above code, we create a JavaFX application window that contains a text area and a text input box. When the user enters text in the input box and presses the Enter key, the program sends the text to the server. After receiving the message from the server, the program will append the message to the text area for display.

Conclusion:
This article introduces how to use JavaFX and WebSocket technology in Java 9 to implement a graphical interface for real-time communication. By mastering the basic knowledge of JavaFX and WebSocket, combined with actual code examples, we can easily implement graphical interface applications with real-time communication capabilities in Java 9. Hope this article is helpful to you!

The above is the detailed content of How to implement a graphical interface for real-time communication using JavaFX and WebSocket in Java 9. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn