(java)websocket服务的两种实现方式
Java中实现WebSocket服务的常见方式有两种:使用Java EE的@ServerEndpoint
注解或使用Spring框架。
- 使用Java EE的
@ServerEndpoint
注解:
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/websocket")
public class WebSocketEndpoint {
private static final CopyOnWriteArraySet<Session> sessions = new CopyOnWriteArraySet<>();
@OnOpen
public void onOpen(Session session) {
sessions.add(session);
System.out.println("Connected ... " + session.getId());
}
@OnClose
public void onClose(Session session) {
sessions.remove(session);
System.out.println("Disconnected ... " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("Received message in endpoint: " + message);
// Broadcast message to all active sessions
for (Session s : sessions) {
try {
s.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("Error for session: " + session.getId());
throwable.printStackTrace();
}
}
- 使用Spring框架:
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.concurrent.ConcurrentHashMap;
public class WebSocketHandler extends TextWebSocketHandler {
private static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) {
sessions.put(session.getId(), session);
System.out.println("Connected ... " + session.getId());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
sessions.remove(session.getId())
评论已关闭