Home > Java > javaTutorial > body text

How to develop Websocket applications using Java

PHPz
Release: 2023-12-02 09:54:37
Original
1257 people have browsed it

How to develop Websocket applications using Java

WebSocket is a new protocol introduced by HTML5, used to establish long connections between clients and servers. Like HTTP, it can run on standard web ports, can also traverse firewalls and proxy servers, and has been widely used in scenarios such as real-time communication and push notifications.

As a powerful programming language, Java also provides various WebSocket-related APIs and libraries. This article will introduce how to use Java to develop Websocket applications and provide specific code examples.

1. Introduction to WebSocket API

Java EE 7 provides JSR-356 Java API for WebSocket, which includes WebSocket client-side and server-side interfaces. You can use Java EE 7 containers (such as GlassFish, Tomcat, etc.) or third-party libraries (such as Jetty, Tyrus, etc.) to implement WebSocket functions.

The core interfaces and classes of Java WebSocket API are as follows:

  • Session: Represents the WebSocket connection session through which messages can be sent and received.
  • Endpoint: Represents the endpoint of WebSocket and implements the core logic of WebSocket, including connection, message transmission, error handling, etc.
  • MessageHandler: Represents the message handler of WebSocket, used to receive and process various types of messages.

WebSocket applications can be easily implemented using the Java WebSocket API. Next we will introduce specific examples.

2. WebSocket application example

This article will introduce the implementation of WebSocket application from the following aspects:

  • Server-side WebSocket endpoint implementation
  • Client-side WebSocket implementation
  • Server-side broadcast message implementation

2.1 Server-side WebSocket endpoint implementation

To implement a WebSocket application on the server side, we need Create a WebSocket endpoint. The simple endpoint code is as follows:

import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint(value = "/chat")
public class ChatEndpoint {

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        // 处理收到的消息
        session.getBasicRemote().sendText("You said: " + message);
    }
}
Copy after login

Specify the URI path of the endpoint through the @ServerEndpoint annotation, here it is "/chat". In the endpoint, the @OnMessage annotation is implemented to receive and process messages sent by the client. In this method, we can process the received message and send a response message to the client.

2.2 Client WebSocket implementation

The client can use javax.websocket client API to implement WebSocket through Java. A simple Java WebSocket client example is given below:

import javax.websocket.ClientEndpoint;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;

@ClientEndpoint
public class ChatClientEndpoint {

    private CountDownLatch latch;

    public ChatClientEndpoint(CountDownLatch latch) {
        this.latch = latch;
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        System.out.println("Received message: " + message);
        latch.countDown();
    }

    public static void main(String[] args) throws Exception {
        final int messageCount = 5;
        final CountDownLatch latch = new CountDownLatch(messageCount);

        URI uri = new URI("ws://localhost:8080/chat");
        ChatClientEndpoint client = new ChatClientEndpoint(latch);

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        container.connectToServer(client, uri);

        for (int i = 0; i < messageCount; i++) {
            String message = "Hello " + i;
            client.sendMessage(message);
            System.out.println("Sent message: " + message);
        }

        latch.await();
        container.close();
    }

    public void sendMessage(String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Copy after login

In the client code, we use the @ClientEndpoint annotation to mark the client's WebSocket endpoint. In the main method, we use WebSocketContainer to connect to the server side and send 5 messages. After receiving the server-side response, the onMessage method will be called for processing, and CountDownLatch will be used to implement the program's synchronous waiting.

2.3 Implementation of server-side broadcast messages

In WebSocket applications, sometimes the server needs to broadcast messages to all clients. Here is a simple example:

import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@ServerEndpoint(value = "/chat")
public class ChatEndpoint {

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

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        // 处理收到的消息
        broadcast("User " + session.getId() + " said: " + message);
    }

    private void broadcast(String message) throws IOException {
        for (Session session : sessions) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
    }
}
Copy after login

In this code, we maintain a list of all WebSocket sessions, add new sessions in the @OnOpen method, and remove sessions in the @OnClose method. At the same time, broadcast messages are sent to all WebSocket sessions in the broadcast method.

3. Summary

WebSocket is a very powerful new protocol that allows programs to establish real-time communication and real-time push functions. Java also provides rich API and library support for WebSocket. This article explains how to develop WebSocket applications using Java and gives specific code examples. I hope this article can be helpful for developing WebSocket applications in Java.

The above is the detailed content of How to develop Websocket applications using Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!