websocket入門例子

項目整體結構圖:javascript

web.xml html

<?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客戶端java

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test ws</title>
</head>
<body>
Test ws
<script type="text/javascript">
	//定義websocket
	var ws = new WebSocket("ws://localhost:8080/web/websocket");

	//鏈接websocket
	ws.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服務端web

 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 chrome
16  * tomcat7.0.69
17  * jdk7.0.79
18  * 1 每一個瀏覽器表明一個用戶,與服務端創建鏈接後,實現服務端與瀏覽器的交互
19  * 2 暴露websocket推送接口,其餘服務端或者業務類調用該接口,向指定用戶進行消息推送
20  * @author caihao
21  *
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 sendMsg
37      * @throws IOException
38      */
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     @OnOpen
50     public void onOpen(Session session) throws IOException {
51         this.session = session;
52         System.out.println(this+"有新鏈接,session="+session+";userid="+userid);
53     }
54 
55     @OnClose
56     public void onClose() {
57         webSocketSet.remove(this.userid);
58         System.out.println(this+";鏈接關閉");
59     }
60 
61     @OnMessage
62     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     @OnError
73     public void onError(Throwable error) {
74         System.out.println(this+";發生錯誤");
75         error.printStackTrace();
76     }
77     
78 
79 }

外部類,調用服務端的推送接口chrome

 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 }
相關文章
相關標籤/搜索