Home  >  Article  >  Java  >  How to use WebSocket for real-time file transfer in Java

How to use WebSocket for real-time file transfer in Java

王林
王林Original
2023-12-17 21:59:06921browse

How to use WebSocket for real-time file transfer in Java

In modern Internet applications, real-time file transfer is an integral part. There are many methods for real-time transmission, and WebSocket is the most commonly used one. The WebSocket API in Java allows you to implement real-time file transfer functionality simply and easily. This article will show you how to use WebSocket for real-time file transfer in Java, while providing some concrete code examples.

Introduction to WebSocket

WebSocket is part of the HTML5 standard and is a network protocol based on TCP. This protocol provides a network capability for bidirectional communication over a single TCP connection, allowing real-time transmission. This is different from the traditional HTTP protocol, which is a stateless protocol and requires a new connection to be established for each request.

The main features of the WebSocket protocol are as follows:

  1. Real-time: WebSocket can maintain a long connection, achieve real-time transmission, and can transfer any type of data between the server and the client. .
  2. Two-way communication: WebSocket supports two-way communication. The server can actively push messages to the client instead of waiting for client requests.
  3. Supports multiple data formats: WebSocket can transmit multiple types of data such as text, binary, etc., and can meet the needs of different types of applications.

Usage of Java WebSocket API

Java8 introduced JSR-356, which is the WebSocket standard API in Java. The main classes of Java WebSocket API are in the javax.websocket package. Its API is mainly divided into two categories. One is the API related to the WebSocket connection itself, and the other is the API related to message processing.

WebSocket connection related API

Endpoint: Represents a WebSocket endpoint that can receive client connection requests and connection disconnection requests.

Session: Represents a WebSocket connection session, used to send and receive text and binary messages.

MessageHandler: WebSocket message processing interface, there are two implementation classes Text and Binary. Users can listen to messages and process them by subscribing to this interface.

API related to WebSocket message processing

OnMessage: The processing method of messages sent by the WebSocket client can be implemented through annotations.

RemoteEndpoint: used to send messages.

Use of WebSocket

In actual development, a WebSocket server and a WebSocket client are usually required. Below we will introduce how to use WebSocket to implement the file transfer function.

WebSocket Server

  1. First, we need to create a WebSocket endpoint. In this endpoint, we can handle WebSocket connection requests and connection disconnection requests, and create Session instances and clients. Establish a session on the client.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.PongMessage;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/filetransfer")
public class FileTransferEndpoint {

    private static final Logger LOGGER = Logger.getLogger(FileTransferEndpoint.class.getName());

    @OnOpen
    public void onOpen(Session session) {
        LOGGER.log(Level.INFO, "Session " + session.getId() + " has opened a connection");
    }

    @OnMessage
    public void onMessage(ByteBuffer message, Session session) {
        LOGGER.log(Level.INFO, "Received ByteBuffer message from " + session.getId());
        try {
            RemoteEndpoint.Basic remote = session.getBasicRemote();
            remote.sendText("Hello, " + message.toString());
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to send ByteBuffer message ", e);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        LOGGER.log(Level.INFO, "Received Text message from " + session.getId() + ": " + message);
        try {
            RemoteEndpoint.Basic remote = session.getBasicRemote();
            remote.sendText("Hello, " + message);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to send Text message ", e);
        }
    }

    @OnMessage
    public void onMessage(PongMessage message, Session session) {
        LOGGER.log(Level.INFO, "Received pong message from " + session.getId() + ": " + message);
    }

    @OnError
    public void onError(Throwable exception, Session session) {
        LOGGER.log(Level.SEVERE, "Session " + session.getId() + " occurred exception ", exception);
    }

    @OnClose
    public void onClose(Session session) {
        LOGGER.log(Level.INFO, "Session " + session.getId() + " has closed the connection");
    }
}
  1. In the above code snippet, we implemented three onMessage methods to handle data of ByteBuffer, String and PongMessage types respectively.
  2. Start the server so that the WebSocket server accepts the client's connection request.
import javax.websocket.WebSocketContainer;
import javax.websocket.server.ServerEndpointConfig;
import org.glassfish.tyrus.server.Server;

public class Main {

    public static void main(String[] args) {
        Server server = new Server("localhost", 8080, "/", null, FileTransferEndpoint.class);

        try {
            server.start();
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            server.stop();
        }
    }
}
  1. In the above code snippet, we created a WebSocket server through the Server class, which listens to the 8080 port of the local machine and connects the client The request is forwarded to the FileTransferEndpoint class for processing.

WebSocket Client

  1. First, we need to create a WebSocket client and connect to the server.
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Scanner;

import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.WebSocketContainer;

public class Client {

    private static Object waitLock = new Object();

    public static void main(String[] args) {
        URI uri;
        try {
            uri = new URI("ws://localhost:8080/filetransfer");
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return;
        }

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();

        try {
            Session session = container.connectToServer(MyClientEndpoint.class, uri);
            synchronized(waitLock) {
                waitLock.wait();
            }
        } catch (DeploymentException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            container.getDefaultSessionMaxIdleTimeout();
        }
    }

    public static class MyClientEndpoint extends Endpoint {

        @Override
        public void onOpen(Session session, EndpointConfig config) {
            session.addMessageHandler(new MessageHandler.Whole<String>() {

                @Override
                public void onMessage(String message) {
                    System.out.println(message);
                }
            });

            try {
                ByteBuffer buffer = ByteBuffer.wrap("Hello World".getBytes());
                session.getBasicRemote().sendBinary(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  1. In the above code snippet, we create a WebSocket client and connect to the ws://localhost:8080/filetransfer URL on the server.
  2. Start the client. The client will send the "Hello World" string to the server and receive the response from the server.

Summary

So far, this article has introduced the method of using WebSocket for real-time file transfer in Java, from the WebSocket protocol, the use of Java WebSocket API, and the implementation of WebSocket server and client Several aspects detail the specific steps to achieve real-time file transfer. Using WebSocket enables efficient and reliable real-time file transfer and is an essential part of modern applications.

The above is the detailed content of How to use WebSocket for real-time file transfer in Java. For more information, please follow other related articles on the PHP Chinese website!

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