Tomcat实现WebSocket即时通讯 & Java实现WebSocket的两种方式
在Java中实现WebSocket的两种常见方式是使用Java EE的@ServerEndpoint
注解和使用javax.websocket.Endpoint
类。
方式一:使用@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) {
for (Session peer : sessions) {
if (!peer.equals(session)) {
try {
peer.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("Error ... " + session.getId());
throwable.printStackTrace();
}
}
方式二:使用Endpoint
类
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.S
评论已关闭