Java8 + Tomcat8 實現Websocket 例子
阿新 • • 發佈:2022-05-02
背景
公司網站上線需要一個實時報價功能,於是想到了 Websocket, 我在多年前就嘗試過Websocket 那時 HTML5標準尚未產生,各家實現均有不同,Websocket 版本也非常多,實現相容也比較複雜,於是放棄Websocket。最近看到Websocket 開始流行起來,相容也不再是障礙。
以下節選自《Netkiller Java 手札》,下面例子實現一個簡單的 Echo Server
目錄
- 7.1. Server
- 7.2. Client
環境:Java8 + Tomcat8
7.1. Server
package websocket; /** * Websocket Server * * @author netkiller<[email protected]> */ import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value = "/echo") public class PriceServer { private Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>()); /** * Callback hook for Connection open events. This method will be invoked * when a client requests for a WebSocket connection. * * @param session * the session which is opened. */ @OnOpen public void onOpen(Session session) { sessions.add(session); } /** * Callback hook for Connection close events. This method will be invoked * when a client closes a WebSocket connection. * * @param session * the session which is opened. */ @OnClose public void onClose(Session session) { sessions.remove(session); } /** * Callback hook for Message Events. This method will be invoked when a * client send a message. * * @param message * The text message * @param session * The session of the client */ @OnMessage public void onMessage(String message, Session session) { System.out.println("Message Received: " + message); for (Session remote : sessions) { System.out.println("Sending to " + remote.getId()); remote.getAsyncRemote().sendText(message); } } }