標籤:其他 sed put dex xmlns print etc googl ted
項目總體結構圖:
web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>web</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list></web-app>
index.htm WS用戶端
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>test ws</title></head><body>Test ws<script type="text/javascript">//定義websocketvar ws = new WebSocket("ws://localhost:8080/web/websocket");//串連websocketws.onopen = function(){var num = Math.ceil(Math.random()*100); var msg = ‘userid=‘+num; console.log("open and send message:"+msg); // 發送訊息 ws.send(msg);};//接收訊息ws.onmessage = function(evt){console.log("get message:"+evt.data)};//關閉串連ws.onclose = function(evt){ console.log("WebSocketClosed!");};//發生異常ws.onerror = function(evt){ console.log("WebSocketError!");};</script></body></html>
SocketServer.java 核心類,WS服務端
1 package com.websocket; 2 3 import java.io.IOException; 4 import java.util.HashMap; 5 import java.util.Map; 6 import javax.websocket.OnClose; 7 import javax.websocket.OnError; 8 import javax.websocket.OnMessage; 9 import javax.websocket.OnOpen;10 import javax.websocket.Session;11 import javax.websocket.server.ServerEndpoint;12 13 /**14 * 環境15 * 瀏覽器:firefox,google chrome16 * tomcat7.0.6917 * jdk7.0.7918 * 1 每個瀏覽器代表一個使用者,與服務端建立串連後,實現服務端與瀏覽器的互動19 * 2 暴露websocket推送介面,其他服務端或者業務類調用該介面,向指定使用者進行訊息推送20 * @author caihao21 *22 */23 //URI註解,無需在web.xml中配置。24 @ServerEndpoint("/websocket")25 public class SocketServer {26 27 28 //瀏覽器與服務端的回話,瀏覽器每new一個WebSocket就建立一個session,關閉或重新整理瀏覽器,session關閉29 private Session session;30 //代表瀏覽器31 private String userid;32 33 /**34 * 推送訊息介面35 * 外部可以進行調用36 * @param sendMsg37 * @throws IOException38 */39 public void sendMsg(String sendMsg) throws IOException{40 System.out.println(this.session+";"+this.userid+";"+sendMsg);41 this.session.getBasicRemote().sendText(sendMsg);42 }43 44 //設定Map,存放每個使用者的串連45 public static Map<String,SocketServer> webSocketSet = new HashMap<String,SocketServer>();46 47 48 49 @OnOpen50 public void onOpen(Session session) throws IOException {51 this.session = session;52 System.out.println(this+"有新串連,session="+session+";userid="+userid);53 }54 55 @OnClose56 public void onClose() {57 webSocketSet.remove(this.userid);58 System.out.println(this+";串連關閉");59 }60 61 @OnMessage62 public void onMessage(String info) throws IOException {63 System.out.println(this+";來自用戶端的訊息:" + info);64 String msg = "服務端接收到了來自用戶端的訊息:"+info;65 if(info.contains("userid")){66 this.userid = info.split("userid=")[1];67 System.out.println(this+",this.session="+this.session+";this.userid="+this.userid);68 webSocketSet.put(userid, this); 69 }70 }71 72 @OnError73 public void onError(Throwable error) {74 System.out.println(this+";發生錯誤");75 error.printStackTrace();76 }77 78 79 }
外部類,調用服務端的推送介面
1 package com.websocket; 2 3 import java.io.IOException; 4 import java.util.Map; 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse;10 11 /**12 * 外部類,調用暴露的推送介面13 */14 @WebServlet("/ServletA")15 public class ServletA extends HttpServlet {16 private static final long serialVersionUID = 1L;17 18 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {19 this.doPost(request, response);20 }21 22 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {23 Map<String,SocketServer> webSocketSet = SocketServer.webSocketSet;24 //遍曆使用者,依據使用者的id向使用者發送指定的內容25 for(Map.Entry<String, SocketServer> entry:webSocketSet.entrySet()){ 26 System.out.println(entry.getKey()+"--->"+entry.getValue()); 27 String key = entry.getKey();28 SocketServer ss = webSocketSet.get(key);29 String sendMsg = "向"+key+"發送訊息";30 ss.sendMsg(sendMsg );31 } 32 33 }34 }
websocket入門例子