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

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
SpringBoot怎么整合WebSocket实现后端向前端发送消息SpringBoot怎么整合WebSocket实现后端向前端发送消息May 11, 2023 pm 02:07 PM

一、什么是websocket接口使用websocket建立长连接,服务端和客户端可以互相通信,服务端只要有数据更新,就可以主动推给客户端。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocketAPI中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。在WebSocketAPI中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

在ThinkPHP6中使用Nginx反向代理Websocket在ThinkPHP6中使用Nginx反向代理WebsocketJun 20, 2023 pm 09:31 PM

在近几年的互联网应用中,Websocket已经成为了一种非常重要的通信协议。ThinkPHP6作为一款优秀的PHP开发框架,也提供了对Websocket的支持。不过,在使用Websocket时,我们通常会涉及到跨域、负载均衡等问题,因此,在这篇文章中,我们将介绍如何在ThinkPHP6中使用Nginx反向代理Websocket。首先,我们需要明确一下Webs

Python服务器编程:实现WebSocket服务端Python服务器编程:实现WebSocket服务端Jun 19, 2023 am 09:51 AM

近年来,WebSocket技术日渐流行,成为了浏览器与服务器之间进行实时通信的标准选择。在Python中,我们可以通过一些成熟的库来实现WebSocket服务端的开发。本文将在介绍WebSocket技术的基础上,探索如何利用Python开发WebSocket服务端。一、什么是WebSocketWebSocket是一种在单个TCP

SpringBoot怎么实现WebSocket即时通讯SpringBoot怎么实现WebSocket即时通讯May 12, 2023 am 09:13 AM

1、引入依赖org.springframework.bootspring-boot-starter-websocketorg.projectlomboklombokcom.alibabafastjson1.2.32、WebSocketConfig开启WebSocketpackagecom.shucha.deveiface.web.config;/***@authortqf*@Description*@Version1.0*@since2022-04-1215:35*/importorg.spri

浏览器支持WebTransport?它能替代WebSockets?浏览器支持WebTransport?它能替代WebSockets?Feb 23, 2023 pm 03:36 PM

许多应用程序,如游戏和直播等场景,需要一种机制来尽可能快地发送消息,同时可以接受无序、不可靠的数据传输方式。本机应用程序虽然可以使用原始 UDP 套接字,但这些在 Web 上不可用,因为它们缺乏加密、拥塞控制、同意发送机制(以防止 DDoS 攻击)。

Spring Boot中使用WebSocket实现推送和通知功能Spring Boot中使用WebSocket实现推送和通知功能Jun 23, 2023 am 11:47 AM

在现代Web应用程序开发中,WebSocket是实现即时通信和实时数据传输的常用技术。SpringBoot框架提供了集成WebSocket的支持,使得开发者可以非常方便地实现推送和通知功能。本文将介绍SpringBoot中如何使用WebSocket实现推送和通知功能,并演示一个简单的实时在线聊天室的实现。创建SpringBoot项目首先,我们需要创建一

PHP+Socket系列之实现websocket聊天室PHP+Socket系列之实现websocket聊天室Feb 02, 2023 pm 04:39 PM

本篇文章给大家带来了关于php+socket的相关知识,其中主要介绍了怎么使用php原生socket实现一个简易的web聊天室?感兴趣的朋友下面一起来看一下,希望对大家有帮助。

如何在Linux中使用WebSocket技术如何在Linux中使用WebSocket技术Jun 18, 2023 pm 07:38 PM

随着现代网络应用程序的增多,WebSocket技术也变得非常流行。它是一项基于TCP协议的长连接技术,可以在客户端和服务器之间创建双向通信管道。在本文中,我们将介绍如何在Linux系统中使用WebSocket技术来创建一个简单的实时聊天应用程序。一、安装Node.js要使用WebSocket,首先需要在Linux系统中安装Node.j

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools