websocket即時通訊
阿新 • • 發佈:2021-07-21
jar
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
java
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.*; @ServerEndpoint(value="/shopWebsocket/{shopId}") public class ShopWebSocket { private static final String SESSION_KEY_PRE = "websocketId"; public static Map<String, Session> sessions = new HashMap<>(); private static String shopId; private Logger log = LoggerFactory.getLogger(ShopWebSocket.class); //連線時執行 @OnOpen public void onOpen(@PathParam("shopId") String shopId, Session session) throws IOException { this.shopId = shopId; log.info("session id: " + session.getId()); log.info("新連線:{}", shopId); sessions.put(shopId, session); } //關閉時執行 @OnClose public void onClose(){ log.info("連線:{} 關閉", this.shopId); sessions.remove(shopId); } //收到訊息時執行 @OnMessage public void onMessage(String message, Session session) throws IOException { log.info("收到使用者{}的訊息{}", this.shopId, message); if (message.equals("ping")) { session.getBasicRemote().sendText("heartCheck"); //回覆使用者 return; } session.getBasicRemote().sendText("收到 " + this.shopId + " 的訊息: " + message); //回覆使用者 } //連線錯誤時執行 @OnError public void onError(Session session, Throwable error){ log.info("使用者id為:{}的連線傳送錯誤", this.shopId); error.printStackTrace(); } /** * 傳送訊息 * @author zhuxiang * @date 3:52 下午 2021/7/19 * @param: shopId * @param: msg * @return void */ public static boolean sendMsg(String shopId, String msg) throws IOException { Session session = sessions.get(shopId); if (session == null) { return false; } session.getBasicRemote().sendText(msg); // 傳送訊息 return true; } /** * 獲取藥店ID * @author zhuxiang * @date 10:54 上午 2021/7/20 * @param: * @return java.util.List<java.lang.String> */ public synchronized static List<String> shopIdList() { List<String> list = new ArrayList<>(); for (String shopId : ShopWebSocket.sessions.keySet()) { list.add(shopId); } return list; } }
js
<!DOCTYPE html> <html> <head> </head> <body> <script src="http://cdn.jsdelivr.net/sockjs/1/sockjs.min.js"></script> <script type="text/javascript"> var ws = null; function openWebSocket(){ //判斷當前瀏覽器是否支援WebSocket if ('WebSocket' in window) { ws = new WebSocket("ws://192.168.0.122:8080/taodoctor/shopWebsocket/user000"); } else { ws = new SockJS("http://localhost:8080/taodoctor/sockjs/myWebSocket/info?type=mall"); } ws.onopen = function () { }; //這個事件是接受後端傳過來的資料 ws.onmessage = function (event) { //根據業務邏輯解析資料 console.log(event); }; ws.onclose = function (event) { }; } openWebSocket(); </script> </body> </html>