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 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:
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!