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

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

Jul 30, 2023 am 10:54 AM
websockets real time communication javafx

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

Introduction:
In today's Internet era, real-time communication is one of the very important functions. For example, real-time updates of stock market conditions, real-time chat, etc. This article will introduce how to use JavaFX and WebSockets in Java 9 to implement a graphical interface for real-time communication.

Part One: Introduction to JavaFX
JavaFX is a Java library for building rich client applications. It provides a powerful graphical interface to easily create various visual effects.

Part 2: Introduction to WebSockets
WebSockets is a technology used for real-time two-way communication between clients and servers. It allows servers to proactively send messages to clients and provides a simple protocol to handle real-time communication.

Part 3: Combination of JavaFX and WebSockets
Now let us take a look at how to combine JavaFX and WebSockets to achieve a graphical interface for real-time communication. First, we need to create a JavaFX application and add the WebSockets library to the project's dependencies.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class RealTimeApplication extends Application {

    private Session session;
    private TextArea messageArea;

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

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Real Time Application");

        VBox vbox = new VBox();

        messageArea = new TextArea();
        messageArea.setEditable(false);

        TextField inputField = new TextField();
        inputField.setOnAction(event -> {
            String message = inputField.getText();
            session.getAsyncRemote().sendText(message);
            inputField.setText("");
        });

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

        primaryStage.setScene(new Scene(vbox, 400, 300));
        primaryStage.show();

        connect();
    }

    @Override
    public void stop() {
        try {
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message) {
        messageArea.appendText(message + "
");
    }

    private void connect() {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            session = container.connectToServer(this, new URI("ws://localhost:8080/ws"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy after login

In the above code, we created a JavaFX application named "RealTimeApplication" and added a TextArea for displaying messages and a TextField for inputting messages. When the user presses the Enter key in the TextField, we use the WebSockets session to send a message to the server. When a message is received from the server, we will display it in the TextArea.

Part 4: Server Side Setup
Next, we need to set up the server side to handle messages from clients and broadcast them to all connected clients. Here, we use Spring Boot to create a simple WebSockets server.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Configuration
    @EnableWebSocketMessageBroker
    public static class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

        @Override
        public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
            registration.setMessageSizeLimit(1024000);
        }

        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/ws").withSockJS();
        }
    }

    @ServerEndpoint(value = "/ws")
    public static class WebSocketServer {

        @OnMessage
        public void onMessage(Session session, String message) throws IOException, EncodeException {
            for (Session client : session.getOpenSessions()) {
                client.getBasicRemote().sendText(message);
            }
        }
    }
}
Copy after login

In the above code, we create a WebSocket server named "WebSocketServer" and bind it to the "/ws" endpoint using the @ServerEndpoint annotation. When a message is received from a client, the server broadcasts it to all connected clients.

Conclusion:
By combining JavaFX and WebSockets, we can easily implement a graphical interface for real-time communication. Whether you're looking for real-time stock market updates or live chat, this technology can be extremely useful. I hope this article has been helpful to you in implementing a graphical interface for real-time communication using JavaFX and WebSockets in Java 9.

Reference link:

  • JavaFX official documentation: https://openjfx.io/javadoc/12/
  • WebSocket official documentation: https://www. w3.org/TR/websockets/
  • Spring Boot official documentation: https://spring.io/projects/spring-boot

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

Statement of this Website
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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to achieve real-time communication using PHP and WebSocket How to achieve real-time communication using PHP and WebSocket Dec 17, 2023 pm 10:24 PM

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages ​​in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

What are the various 2D shapes provided by JavaFX? What are the various 2D shapes provided by JavaFX? Sep 03, 2023 pm 09:41 PM

Below are the various geometric shapes you can draw using JavaFX Lines - A line is a geometric structure that connects two points. javafx.scene.shape. The Line class represents a line in the XY plane. Rectangle - A rectangle is a four-sided polygon with two pairs of parallel and concurrent sides, and all interior angles are right angles. javafx.scene. The Rectangle class represents a rectangle in the XY plane. Circle - A circle is a line forming a closed loop, with each point on it being a fixed distance from the center point. javafx.scene. The Circle class represents a circle in the XY plane. Ellipse - An ellipse is defined by two points, each point is called a focus. If you take any point on the ellipse, the sum of the distances to the focus

How to implement Websockets proxy using Nginx Proxy Manager How to implement Websockets proxy using Nginx Proxy Manager Sep 27, 2023 pm 01:46 PM

How to implement Websockets proxy using NginxProxyManager Websockets is a real-time communication protocol suitable for applications that require two-way communication. NginxProxyManager (NPM for short) is an Nginx-based proxy server that can be used to manage and configure multiple reverse proxy resources. This article will introduce how to use NPM to implement Websockets proxy and provide specific code examples. Install npm first

Display web content using the new JavaFX WebView component in Java 13 Display web content using the new JavaFX WebView component in Java 13 Aug 01, 2023 pm 01:09 PM

Use the new JavaFXWebView component in Java13 to display web content. With the continuous development of Java, JavaFX has become one of the main tools for building cross-platform graphical interfaces. JavaFX provides a wealth of graphics libraries and components, allowing developers to easily create a variety of user interfaces. Among them, the JavaFXWebView component is a very useful component that allows us to display web content in JavaFX applications. In Java13, J

Java Websocket Development Guide: How to achieve real-time communication between client and server Java Websocket Development Guide: How to achieve real-time communication between client and server Dec 02, 2023 am 11:52 AM

Java Websocket Development Guide: How to implement real-time communication between the client and the server, specific code examples are required. With the continuous development of web applications, real-time communication has become an indispensable part of the project. In the traditional HTTP protocol, the client sends a request to the server, and the data can only be obtained after receiving the response. This causes the client to continuously poll the server to obtain the latest data, which will lead to performance and efficiency problems. And WebSocket is for understanding

How to use PHP for server-side push and real-time communication How to use PHP for server-side push and real-time communication Aug 02, 2023 am 09:33 AM

How to use PHP for server-side push and real-time communication With the continuous development of technology and the popularity of the Internet, real-time communication is becoming more and more important in web applications. Server-side push and real-time communication enable developers to send real-time updated data to and interact with clients without the client actively requesting data from the server. In PHP development, we can use some technologies to achieve server-side push and real-time communication, such as: WebSocket, LongPolling, Serve

How to use Java to develop a real-time communication application based on WebSocket How to use Java to develop a real-time communication application based on WebSocket Sep 20, 2023 am 11:03 AM

How to use Java to develop a real-time communication application based on WebSocket. In modern Web applications, real-time communication has become a necessary function. WebSocket technology plays an important role in this regard. WebSocket is a full-duplex communication protocol that allows real-time two-way communication between the server and client. This article will introduce how to use Java to develop a real-time communication application based on WebSocket, and provide some specific code examples. Preparations are beginning

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 Jul 30, 2023 pm 04:57 PM

How to use JavaFX and WebSocket to implement a graphical interface for real-time communication in Java9 Introduction: With the development of the Internet, the need for real-time communication is becoming more and more common. In Java9, we can use JavaFX and WebSocket technology 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 Java9, and attach corresponding code examples. Part One: Ja

See all articles