Home Java javaTutorial Using Websocket for real-time communication in Java API development

Using Websocket for real-time communication in Java API development

Jun 19, 2023 am 09:02 AM
websocket real time communication java api

With the continuous development of the Internet, the real-time requirements of Web applications are getting higher and higher. The traditional HTTP protocol cannot meet the needs of real-time communication because it is a stateless request-response communication method, and the request and response are a one-way short-lived connection. Therefore, in order to meet the needs of real-time communication, Websocket technology was born. Websocket is a full-duplex, long-connection, real-time communication technology that allows the client and server to establish a persistent two-way connection and send data arbitrarily during the communication process.

Java API (Application Programming Interface) as a development language can easily use Websocket for real-time communication. The Java API provides some tool classes and frameworks to make Websocket development simpler and more efficient. This article will introduce how to use Websocket for real-time communication in Java API development from the following aspects.

1. Basic use of Websocket

Java API provides the JSR-356 standard for supporting Websocket technology in the Java language. The Websocket interface in the Java API provides basic methods and event handling methods related to Websocket, and developers can use these methods to implement their own Websocket servers and clients.

Using Java API to develop Websocket programs requires the javax.websocket.server.ServerEndpoint annotation and javax.websocket.OnMessage annotation. Among them, the @ServerEndpoint annotation is used to specify the URL, encoding method (such as UTF-8), message processor (ie WebSocketHandler) and other configuration information of the Websocket service. The @OnMessage annotation is used to declare a message processing method of a specified type, which will be called when the Websocket service receives a message sent by the client. When the client sends a message, the message will be extracted and parsed, and then passed to the specified message processing method for processing. Message processing methods can send response messages through Websocket Session objects.

The following is a simple sample code:

@ServerEndpoint(value = "/test")
public class WebSocketDemo {

    @OnMessage
    public String handleMessage(String message, Session session) {
        System.out.println("Received message: " + message);
        String echoMsg = "Echo from server: " + message;

        // 发送响应消息
        try {
            session.getBasicRemote().sendText(echoMsg);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return echoMsg;
    }
}
Copy after login

The above code defines a WebSocket processor named WebSocketDemo, bound to the URL "/test". When the client sends a message, WebSocketDemo's handleMessage method will be called and a response message will be sent.

2. Use Spring Boot to simplify Websocket development

Spring Boot is a development framework based on the Spring framework, and it can also support Websocket well. By using Spring Boot, it is easier to integrate Websocket technology into Java API projects, thus accelerating application development.

First, you need to add the following dependencies in the pom.xml file of the Spring Boot project:

<dependency> 
   <groupId>org.springframework.boot</groupId> 
   <artifactId>spring-boot-starter-websocket</artifactId> 
</dependency>
Copy after login

Then, you need to define the WebSocketHandler class in the Spring Boot application. The WebSocketHandler class needs to inherit from Spring's WebSocketHandler interface and implement some basic methods, such as the handleTextMessage() method, for processing text messages sent by the client:

public class MyHandler extends TextWebSocketHandler {

   @Override
   public void handleTextMessage(WebSocketSession session, TextMessage message) 
           throws InterruptedException, IOException { 

        String payload = message.getPayload(); 

        // 处理消息
        String echoMsg = "Echo from server: " + payload;

        // 发送响应消息
        session.sendMessage(new TextMessage(echoMsg)); 
   } 

}
Copy after login

Finally, it needs to be in the configuration file of the Spring Boot application Configure WebSocket in as follows:

@Configuration 
@EnableWebSocket 
public class WebSocketConfig implements WebSocketConfigurer { 

    @Override 
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { 

        registry.addHandler(new MyHandler(), "/myHandler").setAllowedOrigins("*"); 
   } 

}
Copy after login

In the above code, the MyHandler class will be bound to the URL "/myHandler" and set to allow cross-domain requests. You can implement your own WebSocket handler, modify the URL, or use other configuration options. Using Spring Boot can provide a lot of convenience for Websocket development and simplify the development process.

3. Use Javascript to develop Websocket client

While using Java API to develop Websocket server, we need to develop Websocket client to communicate with the server. Javascript's websocket API allows us to easily use Websockets to implement client communication in web applications.

To use Websocket in Javascript, you first need to create a Websocket object and specify the Websocket server address:

var ws = new WebSocket("ws://localhost:8080/test");
Copy after login

Then, you can use the following code to send a message and receive a response message from the Websocket server:

ws.onopen = function() {
   alert("Websocket连接已建立!");
   ws.send("Hello world!");
}; 

ws.onmessage = function(evt) {
   var receivedMsg = evt.data;
   alert("Received message: " + receivedMsg);
   ws.close();
};
Copy after login

The above code will connect to the Websocket server with the URL ws://localhost:8080/test and send a message containing the string "Hello world!". When the server processes the message, it sends a response message, and eventually the client receives the response message and closes the connection.

4. Websocket implements chat room-like applications

Through the above introduction, I believe you have understood how to use Java API for Websocket programming and how to use Javascript client to communicate with it. Next, we can try to use Websocket to implement a simple chat room application.

First, you need to use Java API to implement a Websocket processor to process messages sent by the Websocket client:

@ServerEndpoint(value = "/chat/{username}")
public class ChatServer {

    private static Set<Session> clients = Collections.synchronizedSet(new HashSet<>());

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        // 将用户加入到聊天室中
        clients.add(session);

        // 广播消息
        broadcast(username, " joined the chat room!");
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("username") String username) {
        // 广播消息
        broadcast(username, ": " + message);
    }

    @OnClose
    public void onClose(Session session, @PathParam("username") String username) {
        // 将用户从聊天室中移除
        clients.remove(session);

        // 广播消息
        broadcast(username, " left the chat room!");
    }

    private static void broadcast(String username, String message) {
        // 向所有用户广播消息
        for (Session client : clients) {
            try {
                client.getBasicRemote().sendText(username + message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Copy after login

以上代码定义了一个名为 ChatServer 的 Websocket 处理器,绑定到 URL “/chat/{username}”。当客户端连接到聊天室时,ChatServer 的 onOpen 方法将被调用,并将客户端添加到 clients 集合中,然后广播一条 “加入聊天室” 的消息。当客户端在聊天室中发送一条消息时,ChatServer 的 onMessage 方法将被调用,并向聊天室的所有客户端广播一条消息。当客户端离开聊天室时,ChatServer 的 onClose 方法将被调用,并将客户端从 clients 集合中移除,然后广播一条 “离开聊天室” 的消息。

然后,需要使用简单的 HTML 和 Javascript 代码实现一个 Websocket 客户端:

<!DOCTYPE html>
<html>
<head>
   <title>Chat room</title>
</head>
<body>
   <h1>Chat room</h1>
   <div id="messageArea"></div>
   <form>
       <input type="text" id="inputField" onkeydown="return send(event)">
   </form>

   <script>
       var ws = new WebSocket("ws://localhost:8080/chat/"+prompt("Please enter your name:"));

       ws.onmessage = function(evt) {
           var receivedMsg = evt.data;
           var messageArea = document.getElementById("messageArea");
           messageArea.innerHTML += receivedMsg + "<br>";
       };

       function send(event) {
           if (event.keyCode == 13) {
               event.preventDefault();
               var inputField = document.getElementById("inputField")
               ws.send(inputField.value);
               inputField.value = "";
               return false;
           }
       }
   </script>
</body>
</html>
Copy after login

以上代码将会要求用户输入他们的名称,然后使用 Websocket 连接到 ChatServer 上。用户可以在输入框中输入文本并按下回车键进行发送。当接收到来自 ChatServer 的消息时,HTML 页面将在聊天窗口底部添加一条新的消息。

通过使用 Java API 和 Websocket 技术,我们可以方便地实现高效、实时的 Web 应用程序。无论你是在开发聊天室、在线游戏还是其他实时 Web 应用程序,Websocket 都可以是一个很好的选择。现在开始尝试使用 Websocket,构建自己的实时 Web 应用程序吧!

The above is the detailed content of Using Websocket for real-time communication in Java API development. 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

Video Face Swap

Video Face Swap

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

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

PHP and WebSocket: Best practices for real-time data transfer PHP and WebSocket: Best practices for real-time data transfer Dec 18, 2023 pm 02:10 PM

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

How does Java Websocket implement online whiteboard function? How does Java Websocket implement online whiteboard function? Dec 17, 2023 pm 10:58 PM

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

SSE and WebSocket SSE and WebSocket Apr 17, 2024 pm 02:18 PM

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration

What are the free API interface websites? What are the free API interface websites? Jan 05, 2024 am 11:33 AM

Free api interface website: 1. UomgAPI: a platform that provides stable and fast free API services, with over 100 API interfaces; 2. free-api: provides multiple free API interfaces; 3. JSON API: provides free data API interface; 4. AutoNavi Open Platform: Provides map-related API interfaces; 5. Face recognition Face++: Provides face recognition-related API interfaces; 6. Speed ​​data: Provides over a hundred free API interfaces, suitable for various needs In the case of data sources; 7. Aggregate data, etc.

golang WebSocket programming tips: handling concurrent connections golang WebSocket programming tips: handling concurrent connections Dec 18, 2023 am 10:54 AM

Golang is a powerful programming language, and its use in WebSocket programming is increasingly valued by developers. WebSocket is a TCP-based protocol that allows two-way communication between client and server. In this article, we will introduce how to use Golang to write an efficient WebSocket server that handles multiple concurrent connections at the same time. Before introducing the techniques, let's first learn what WebSocket is. Introduction to WebSocketWeb

How to use WebSocket for file transfer in golang How to use WebSocket for file transfer in golang Dec 18, 2023 am 09:06 AM

How to use WebSocket for file transfer in golang WebSocket is a network protocol that supports two-way communication and can establish a persistent connection between the browser and the server. In golang, we can use the third-party library gorilla/websocket to implement WebSocket functionality. This article will introduce how to use golang and gorilla/websocket libraries for file transfer. First, we need to install gorilla

PHP Websocket development guide to implement real-time translation function PHP Websocket development guide to implement real-time translation function Dec 18, 2023 pm 05:52 PM

PHP Websocket Development Guide: Implementing Real-time Translation Function Introduction: With the development of the Internet, real-time communication is becoming more and more important in various application scenarios. As an emerging communication protocol, Websocket provides good support for real-time communication. This article will take you through a detailed understanding of how to use PHP to develop Websocket applications, and combine the real-time translation function to demonstrate its specific application. 1. What is the Websocket protocol? The Websocket protocol is a

See all articles