SoFunction
Updated on 2025-03-04

Detailed explanation of the Websocket example in daily development of JAVA

JAVA | Detailed explanation of Websocket in daily development,WebSocket is a protocol for full-duplex communication on a single TCP connection. It realizes real-time data transmission between clients and servers in web applications. Unlike HTTP, after WebSocket establishes a connection, both the client and the server can send data to the other party at any time without the need to establish a new connection every time HTTP requests. This makes WebSocket very suitable for scenarios that require real-time communication, such as online chat, real-time notifications, stock market push, etc. This article will introduce the use of WebSocket in Java development in detail, including basic concepts, Java API, usage examples and precautions.

Preface

In an era of surging digital waves, program development is like a mysterious and magnificent magic castle, standing in the vast starry sky of technology. The characters in the code are like the twinkling stars, combined, intertwined and collided according to specific trajectories and rhythms, and are about to embark on a wonderful and creative journey full of infinite possibilities. When the blank document interface is like a deep universe waiting to be explored, programmers transform into fearless star pioneers, dancing lightly on the keyboard with their fingertips, preparing to use wisdom and logic to weave a program scroll that is enough to change the rules of the world's operation, and in the binary world of 0 and 1, they engrave the immortal mark of human innovation and breakthrough.

1. Websocket Overview

1.1 Definition

Websocket is a protocol for full duplex communication on a single TCP connection. It allows real-time, bidirectional data transmission between the client and the server. Unlike traditional HTTP request-response mode, HTTP is one-way, and the client requests, and the connection is closed after the server responds, while the Websocket keeps the connection open to exchange data at any time.
For example, in a live chat application, Websocket allows clients (such as browsers) to send and receive chat messages in real time between a client (such as a browser) and a server without having to send requests as frequently as traditional HTTP polling to check for new messages.

1.2 Advantages

High real-time performance: It can realize real-time communication between the server and the client, and data can be transmitted between the two parties in real time, reducing latency. This is very critical for application scenarios that require real-time update of data, such as stock trading platforms, online games, etc.
Efficient and energy-saving: Compared with traditional HTTP polling (the client sends requests to the server regularly to obtain the latest information), Websocket avoids the overhead of frequent establishment and disconnection, thus saving network resources and server resources and improving efficiency.
Cross-platform support: The Websocket protocol is based on the TCP protocol and has good support in modern browsers and most server environments, making it convenient for developing cross-platform real-time applications.

2. Websocket protocol basics

2.1 Handshake Process

The Websocket protocol requires a handshake when establishing a connection. The client first sends an HTTP request to the server, which contains some special header information to indicate that this is a Websocket request. For example, the request header contains the Upgrade: websocket and Connection: Upgrade fields that request the upgrade of the protocol from HTTP to the Websocket.
After the server receives the request, if the Websocket protocol is supported and the upgrade is agreed, it will return a response containing 101 Switching Protocols status code, indicating that the protocol switching is successful, and then both parties establish a Websocket connection.

2.2 Message format

Websocket messages mainly have two formats: text format and binary format. Messages are transmitted in frames, and a complete message can be composed of one or more frames.
Text messages are transmitted in UTF-8 encoding, which facilitates processing of text data, such as chat messages. Binary format is suitable for transmitting binary data such as images, audio, and video.

2.3 Data transmission method

Full-duplex communication means that both the client and the server can actively send messages. After the connection is established, either party can send data at any time and does not need to wait for the other party's request. For example, the server can actively push real-time stock price changes to the client, and the client can also send trading instructions to the server.

3. Use Websocket in Java

3.1 Java WebSocket API(JSR - 356)

Introduction: Java provides the WebSocket API to easily implement Websocket functions in Java applications. This API defines the client-side and server-side interfaces, allowing developers to easily build Websocket applications.

Server-side implementation example:

First, create a class annotated @ServerEndpoint to represent the Websocket server endpoint.

import ;
import ;
@ServerEndpoint("/chat")
public class ChatServer {
    @OnMessage
    public String onMessage(String message) {
        // Simple message processing, such as converting messages to capitalization        return ();
    }
}

In the above example, the @ServerEndpoint("/chat") annotation defines the path to the Websocket server endpoint as /chat. The @OnMessage annotation tag method will be called when the message is received, here it simply converts the received message to uppercase and returns.

Client implementation example:

The client needs to create a WebSocketContainer to establish the connection and send and receive messages.

import ;
import ;
import ;
public class ChatClient {
    public static void main(String[] args) {
        try {
            WebSocketContainer container = ();
            String uri = "ws://localhost:8080/chat";
             session = (, new URI(uri));
            // Send a message            ().sendText("Hello");
            // Receive message            String response = ().receiveText();
            ("Received: " + response);
        } catch (Exception e) {
            ();
        }
    }
}

In this client example, first get the WebSocketContainer and then connect to the server endpoint via the connectToServer method. After that, you can use sendText to send messages and receiveText to receive messages.

3.2 Third-party libraries (such as Tyrus)

Introduction: Tyrus is a popular Websocket implementation library that provides rich functionality and better performance. It is a reference implementation of the Java EE specification and supports the JSR-356 standard.

Sample code (server side):

Add Tyrus dependencies to the project (taking Maven as an example).

<dependency>
    <groupId> - servlet</groupId>
    <artifactId>tyrus - servlet</artifactId>
    <version>1.15</version>
</dependency>

Create a server endpoint class.

import ;
public class TyrusChatServer {
    public static void main(String[] args) {
        Server server = new Server("localhost", 8080, "/", null, );
        try {
            ();
            ("Server started");
            // Keep the server running            (Long.MAX_VALUE);
        } catch (Exception e) {
            ();
        } finally {
            ();
        }
    }
}

The ChatServerEndpoint class can be similar to the server endpoint class definition in the previous JSR - 356, and is used to process messages.

Sample code (client):

The Tyrus client dependency is also required.

<dependency>
    <groupId> - client</groupId>
    <artifactId>tyrus - client</artifactId>
    <version>1.15</version>
</dependency>

Client connection and message sending and receiving examples.

import ;
import ;
import ;
import ;
public class TyrusChatClient {
    public static void main(String[] args) {
        try {
            ClientManager clientManager = new ClientManager();
            String uri = "ws://localhost:8080/chat";
            Session session = (, new URI(uri));
            // Send a message            ().sendText("Hello");
            // Receive message            String response = ().receiveText();
            ("Received: " + response);
        } catch (Exception e) {
            ();
        }
    }
}

IV. Application scenarios

4.1 Live Chat Application

This is one of the most typical application scenarios of Websocket. The user opens the chat interface in the browser and establishes a connection with the server through Websocket. When a user sends a chat message, the message is transmitted to the server instantly through the Websocket, and the server forwards the message to the client of other relevant users to realize the real-time chat function.

4.2 Real-time data push (such as stock market, sports event scores)

For applications that require real-time update of data, such as stock market monitoring applications in the financial field, Websocket allows the server to push the latest price to the client immediately when the stock price changes. The update of sports events scores is similar. Viewers can see the score changes in real time in the browser without manually refreshing the page.

4.3 Online Games

In multiplayer online games, Websocket is used to synchronize player operations and game status in real time. For example, in a multiplayer competitive game, players' movements, attacks and other operations can be transmitted to the server instantly through Websocket, and the server then broadcasts this information to other players to ensure the real-time and fairness of the game.

Conclusion

Dear friend, no matter how long and rugged the road ahead is, please keep the spark of your dreams, because in the vast starry sky of life, there is always a brilliant star that belongs to you shining brightly, waiting for you to arrive.

May you always reap small and certain happiness in this complex world, like the spring breeze blowing on your face, all your fatigue and worries can be treated gently, and your heart will always be filled with peace and comfort.

At this point, the article is coming to an end, and your story is still being written. I wonder what unique insights do you have about the description in the article? We look forward to your conversation with me in your heart and opening up a new exchange of your thoughts.

This is the end of this article about the detailed explanation of the Websocket example in JAVA daily development. For more related java Websocket content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!