温馨提示×

java实现websocket如何处理连接

小樊
123
2024-11-21 22:58:50
栏目: 编程语言

在Java中,我们可以使用Java API for WebSocket (JSR 356)来处理WebSocket连接。以下是一个简单的示例,展示了如何使用Java Servlet API创建一个WebSocket端点来处理客户端连接。

  1. 首先,确保你的项目已经包含了Java WebSocket库。如果你使用的是Maven,可以在pom.xml文件中添加以下依赖:
<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.1</version>
</dependency>
  1. 创建一个WebSocket端点类,例如MyWebSocketEndpoint.java
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 = "/my-websocket", configurator = MyWebSocketConfigurator.class)
public class MyWebSocketEndpoint {

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

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

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

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

    @OnError
    public void onError(Throwable error) {
        System.err.println("Error occurred: " + error.getMessage());
    }

    private void broadcastMessage(String message) {
        for (Session session : sessions) {
            if (session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    System.err.println("Error sending message to session " + session.getId() + ": " + e.getMessage());
                }
            }
        }
    }
}
  1. 创建一个配置类,例如MyWebSocketConfigurator.java,用于设置WebSocket端点的属性(如果需要):
import javax.websocket.server.ServerEndpointConfig;

@ServerEndpointConfig(configurator = MyWebSocketConfigurator.class)
public class MyWebSocketConfigurator extends ServerEndpointConfig.Configurator {
    // 可以在这里设置端点的属性,如果需要的话
}
  1. 创建一个WebSocket服务器,例如WebSocketServer.java
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(MyWebSocketEndpoint.class);

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

现在,当你运行WebSocketServer类时,它将启动一个WebSocket服务器,监听端口8080上的/my-websocket路径。当客户端连接到这个端点时,MyWebSocketEndpoint类中的onOpen方法将被调用,并将客户端会话添加到sessions集合中。当客户端发送消息时,onMessage方法将被调用,并将消息广播给所有连接的客户端。

0