1.兩種方式,一種使用tomcat的websocket實現,一種使用spring的websocket
2.tomcat的方式需要tomcat 7.x,JEE7的支持。
3.spring與websocket整合需要spring 4.x,并且使用了socketjs,對不支持websocket的瀏覽器可以模擬websocket使用
二、方式一:tomcat使用這種方式無需別的任何配置,只需服務端一個處理類,
服務器端代碼
package com.Socket; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import net.sf.json.JSONObject; @ServerEndpoint("/websocket/{username}") public class WebSocket { private static int onlineCount = 0; private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>(); private Session session; private String username; @OnOpen public void onOpen(@PathParam("username") String username, Session session) throws IOException { this.username = username; this.session = session; addOnlineCount(); clients.put(username, this); System.out.println("已連接"); } @OnClose public void onClose() throws IOException { clients.remove(username); subOnlineCount(); } @OnMessage public void onMessage(String message) throws IOException { JSONObject jsonTo = JSONObject.fromObject(message); if (!jsonTo.get("To").equals("All")){ sendMessageTo("給一個人", jsonTo.get("To").toString()); }else{ sendMessageAll("給所有人"); } } @OnError public void onError(Session session, Throwable error) { error.printStackTrace(); } public void sendMessageTo(String message, String To) throws IOException { // session.getBasicRemote().sendText(message); //session.getAsyncRemote().sendText(message); for (WebSocket item : clients.values()) { if (item.username.equals(To) ) item.session.getAsyncRemote().sendText(message); } } public void sendMessageAll(String message) throws IOException { for (WebSocket item : clients.values()) { item.session.getAsyncRemote().sendText(message); } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocket.onlineCount++; } public static synchronized void subOnlineCount() { WebSocket.onlineCount--; } public static synchronized Map<String, WebSocket> getClients() { return clients; } }
網站題目:java實現websocket的兩種方式實例詳解-創新互聯
本文來源:http://vcdvsql.cn/article24/cedgce.html
成都網站建設公司_創新互聯,為您提供網站內鏈、小程序開發、微信公眾號、網站策劃、品牌網站建設、做網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯