Java

java如何实现websocket通讯

小亿
82
2024-12-07 08:59:37
栏目: 编程语言

在Java中实现WebSocket通信,你可以使用Java API for WebSocket (JSR 356) 或者一些流行的库,如Spring Boot和Tyrus。下面是一个简单的示例,展示了如何使用Java API for WebSocket创建一个基本的WebSocket服务器。

  1. 首先,确保你的项目中包含了Java WebSocket API。如果你使用的是Maven,可以在pom.xml文件中添加以下依赖:
<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.1</version>
</dependency>
  1. 创建一个WebSocket服务器端点类:
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@ServerEndpoint(value = "/websocket")
public class WebSocketServer {

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

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        System.out.println("New client connected: " + session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Received message from client " + session.getId() + ": " + message);
        broadcastMessage("Message from server: " + message);
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        System.out.println("Client disconnected: " + session.getId());
    }

    @OnError
    public void onError(Exception error) {
        System.err.println("Error in WebSocket server: " + error.getMessage());
    }

    private void broadcastMessage(String message) {
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                System.err.println("Error sending message to client: " + e.getMessage());
            }
        }
    }
}
  1. 创建一个WebSocket服务器类,用于启动服务器并注册WebSocket端点:
import javax.websocket.server.Server;
import java.util.HashSet;
import java.util.Set;

public class WebSocketServer {

    public static void main(String[] args) {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(WebSocketServer.class);

        Server server = new Server("localhost", 8080, classes);
        try {
            server.start();
            System.out.println("WebSocket server started on port 8080");
            server.wait();
        } catch (Exception e) {
            System.err.println("Error starting WebSocket server: " + e.getMessage());
        }
    }
}

现在,当你启动WebSocket服务器并访问ws://localhost:8080/websocket时,你将能够与服务器进行实时通信。你可以使用任何支持WebSocket的客户端库来测试这个服务器。

0
看了该问题的人还看了