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:
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
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"); } }
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(); } } }
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
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(); } } } }
ws://localhost:8080/filetransfer
URL on 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!