首页 > 代码库 > websocket入门例子

websocket入门例子

项目总体结构图:

技术分享

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">
	//定义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服务端

 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 one rror(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入门例子