Home Java javaTutorial WebSockets and real-time communication in Java network programming

WebSockets and real-time communication in Java network programming

May 09, 2024 pm 09:42 PM
network programming

WebSocket is a two-way communication protocol that allows a low-latency, persistent connection between a web client and a server and is widely used to build real-time communication applications such as chat and online games. In Java, you can use the WebSocket API or a third-party library such as Spring WebSocket. Establishing a connection using the WebSocket API involves the following steps: establishing an HTTP connection, handshake, and upgrading to WebSocket. A common use case is building multi-player chat applications where the server endpoint handles messages via a Servlet and clients can connect to the server via JavaScript WebSocket objects and send and receive messages.

Java 网络编程中的 WebSocket 和实时通信

WebSocket and real-time communication in Java network programming

WebSocket is a two-way full-duplex communication protocol that allows web clients to Establish a low-latency, persistent connection between the client and the server. It is widely used to build real-time communication applications such as chat, real-time collaboration, and online gaming.

Introduction to WebSocket Protocol

WebSocket is a protocol that runs on top of an HTTP-based protocol (usually WebSocket). Establishing a WebSocket connection involves the following steps:

  1. Establishing an HTTP connection: The client sends an HTTP GET request with the Upgrade: websocket header.
  2. Handshake: The server returns a 101 Switching Protocols response, which contains the WebSocket key.
  3. Upgrade to WebSocket: The client sends an HTTP response with a WebSocket key to upgrade to a WebSocket connection.

Using WebSocket in Java

To use WebSocket in Java, you can leverage the Java WebSocket API or a third-party library such as Spring WebSocket. This section explores examples of using the WebSocket API.

// 创建 WebSocket 服务器端点
WebSocketServer ws = new WebSocketServer() {

    @Override
    public void onOpen(WebSocket websocket, ClientEndpointConfig cec) {
        System.out.println("客户端已连接");
    }

    @Override
    public void onMessage(String message, WebSocket websocket) {
        System.out.println("收到客户端消息:" + message);
    }

    @Override
    public void onClose(WebSocket websocket) {
        System.out.println("客户端已断开连接");
    }

    @Override
    public void onError(WebSocket websocket, Throwable cause) {
        System.err.println("WebSocket 发生错误:" + cause.getMessage());
    }
};

ws.start();
Copy after login
// 创建 WebSocket 客户端端点
WebSocketClient wsClient = new WebSocketClient() {

    @Override
    public void onOpen(ServerEndpointConfig sec) {
        System.out.println("连接到服务器");
    }

    @Override
    public void onMessage(String message, Session session) {
        System.out.println("收到服务器消息:" + message);
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("连接已关闭");
    }

    @Override
    public void onError(Session session, WebSocketError error) {
        System.err.println("WebSocket 发生错误:" + error.getMessage());
    }
};

wsClient.open("ws://localhost:8080/websocket");
Copy after login

Practical case: Chat application

Using WebSocket, you can easily build a multi-person chat application. Here is an example:

// 服务器端:
@WebServlet("/chat")
public class ChatServlet extends HttpServlet {

    private Set<WebSocket> webSockets = new HashSet<>();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        String message = req.getParameter("message");
        for (WebSocket ws : webSockets) {
            ws.sendString(message);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("ws", new WebSocket(req, resp));
        req.getRequestDispatcher("/chat.jsp").forward(req, resp);
    }

    public void onOpen(WebSocket socket) {
        webSockets.add(socket);
    }

    public void onClose(WebSocket socket) {
        webSockets.remove(socket);
    }
}

// 客户端:
<script type="text/javascript">
    var ws = new WebSocket("ws://localhost:8080/chat");

    ws.onopen = function() {
        console.log("连接已建立");
    };

    ws.onmessage = function(event) {
        console.log("收到消息:" + event.data);
    };

    ws.onclose = function() {
        console.log("连接已关闭");
    };

    function sendMessage() {
        var message = document.getElementById("message").value;
        ws.send(message);
    }
</script>
Copy after login

The above is the detailed content of WebSockets and real-time communication in Java network programming. 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)

What are the c++ open source libraries? What are the c++ open source libraries? Apr 22, 2024 pm 05:48 PM

C++ provides a rich set of open source libraries covering the following functions: data structures and algorithms (Standard Template Library) multi-threading, regular expressions (Boost) linear algebra (Eigen) graphical user interface (Qt) computer vision (OpenCV) machine learning (TensorFlow) Encryption (OpenSSL) Data compression (zlib) Network programming (libcurl) Database management (sqlite3)

How do C++ functions handle DNS queries in network programming? How do C++ functions handle DNS queries in network programming? Apr 27, 2024 pm 06:39 PM

The C++ standard library provides functions to handle DNS queries in network programming: gethostbyname(): Find host information based on the host name. gethostbyaddr(): Find host information based on IP address. dns_lookup(): Asynchronously resolves DNS.

How many levels are there in the Python exam? How many levels are there in the Python exam? Apr 02, 2024 pm 06:00 PM

There are 12 levels of Python exams, from beginner to advanced, in order to master Python's basic syntax, advanced features, advanced concepts and underlying mechanisms, etc., with gradually increasing difficulty.

What are the common protocols for Java network programming? What are the common protocols for Java network programming? Apr 15, 2024 am 11:33 AM

Commonly used protocols in Java network programming include: TCP/IP: used for reliable data transmission and connection management. HTTP: used for web data transmission. HTTPS: A secure version of HTTP that uses encryption to transmit data. UDP: For fast but unstable data transfer. JDBC: used to interact with relational databases.

How does Java network programming use UDP for connectionless communication? How does Java network programming use UDP for connectionless communication? Apr 15, 2024 pm 12:51 PM

UDP (User Datagram Protocol) is a lightweight connectionless network protocol commonly used in time-sensitive applications. It allows applications to send and receive data without establishing a TCP connection. Sample Java code can be used to create a UDP server and client, with the server listening for incoming datagrams and responding, and the client sending messages and receiving responses. This code can be used to build real-world use cases such as chat applications or data collection systems.

Golang common function address resolution guide Golang common function address resolution guide Apr 08, 2024 pm 02:18 PM

The key functions for parsing addresses in the Go language include: net.ParseIP(): Parse IPv4 or IPv6 addresses. net.ParseCIDR(): Parse CIDR tags. net.ResolveIPAddr(): Resolve hostname or IP address into IP address. net.ResolveTCPAddr(): Resolve host names and ports into TCP addresses. net.ResolveUDPAddr(): Resolve host name and port into UDP address.

How do C++ functions implement network security in network programming? How do C++ functions implement network security in network programming? Apr 28, 2024 am 09:06 AM

C++ functions can achieve network security in network programming. Methods include: 1. Using encryption algorithms (openssl) to encrypt communication; 2. Using digital signatures (cryptopp) to verify data integrity and sender identity; 3. Defending against cross-site scripting attacks ( htmlcxx) to filter and sanitize user input.

How long does it take to learn golang How long does it take to learn golang Apr 02, 2024 pm 07:48 PM

The time it takes to master Golang varies from person to person, but it usually takes a few months to a few years. Learning stages include: Basic (1-2 months), Intermediate (3-6 months), Advanced (6-12 months or longer). Factors that accelerate learning include ongoing practice, project work, community involvement, and online resources. Influencing factors include prior programming experience, frequency of study, and study materials.

See all articles