


How to use JavaFX and WebSockets in Java 9 to implement a graphical interface for real-time communication
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(); } } }
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); } } } }
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!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
