1. 程式人生 > >Web Socket 多個使用者之間實現時時訊息推送

Web Socket 多個使用者之間實現時時訊息推送

1個月不寫部落格了,最近挺忙的,剛用了2天寫了個預約的小程式和大家分享下~

首先大家看下介面:

1.祕書端 - 專門新增預約的內容,新增以後立馬在 市長端” 彈出有一個新的預約

2.市長端 - 專門看最新的預約 ,看看要不要接待,接待或不接待點選按鈕以後以後立馬 回覆祕書

其實挺簡單的一個需求啊,但是其中用到的東西還真是挺多的

1.socket server端 和 web socket client端 中的訊息時時分發到各個 client端
2. ajax json 資料查詢和UI渲染包括一些css的動畫

setp1. 我先按照web的做法把ui和各個頁面的效果做出來

setp2. 完善好所有不是實時同步的業務流程

setp3. 根據websocket 分發的資料,挑選是自己的,audio提示:您有一個新的訊息,然後呼叫ajax重新整理資料來實現實時同步

setp4. 新增完或者接待完 使用send (admin_id,to_admin_id) 方法推送給某個人,然後某個人的ui進行重新ajax渲染


部分程式碼:

web socket client 端 api.jsp 把所用同步的回撥方法和上線,下線,傳送,播放聲音都放在一個jsp中 需要的頁面直接:iframe引入

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/config.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>web socket api</title>
    <base href="<%=$.root() %>" />
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  <body>
  	<audio id="audio" preload="auto" controls="controls" height="100" width="100">
		    <source src="qiyulin/song.ogg" type="audio/ogg" />
		    <source src="qiyulin/song.mp3" type="audio/mp3" />
		 	<embed height="100" width="100" src="qiyulin/song.mp3" />
	</audio>
  	<script type="text/javascript"> var tcp_url='<%=tcp_url %>'; </script>
    <script type="text/javascript" src="qiyulin/prototype.js"></script>
    <script type="text/javascript">
		var ws =null;
		//play
		var play = function(){
			var audio = document.getElementById('audio');
    		audio.play();
		}
		
		//offline
		var offline = function(){
			 log("[WebSocket#close]\n");
             if (ws!=null) {
	             ws.close();
	             ws = null;
	         }
		}
		
		//online 
		var online = function(){
			 if(ws==null){
			      ws = new WebSocket(tcp_url);
			      ws.onopen = function() {
			             log("[WebSocket#onopen]\n");
			             window.parent.online();
			       }
			       ws.onmessage = function(e) {
			            log("[WebSocket#onmessage] Message: '" + e.data + "'\n");
			            window.parent.message(e.data);
			        }
			       ws.onclose = function() {
			            log("[WebSocket#onclose]\n");
			             if (ws) {
				             ws.close();
				             ws = null;
				         }
				         window.parent.offline();
			        }
		        }
		}
		
		//send
		var send = function(admin_id,to_admin_id){
			if(ws!=null){
				var json ='{"admin_id":'+admin_id+',"to_admin_id":'+to_admin_id+'}';
				ws.send(json);
			}else{
				online();
				var json ='{"admin_id":'+admin_id+',"to_admin_id":'+to_admin_id+'}';
				ws.send(json);
			}
		}
		
		 function log(text) {
	        var str=(new Date).getTime() + ": " + (!Object.isUndefined(text) && text !== null ? text.escapeHTML() : "null") ;
	     	console.log(str);
	     }
		
		document.observe("dom:loaded", function() {
		  	 if (!window.WebSocket) {
		          alert("不支援WebSocket!");
		          return;
		      }
			 online();
		});
    </script>
  </body>
</html>

socket server端 因為是web的,所以在web.xml中配置 一個ContextListener

public class TcpServerListener  implements ServletContextListener{
	
	private TcpServer s;
	
	public void contextInitialized(ServletContextEvent arg0) {
		int port = 8887;
		try {
			s = new TcpServer( port );
			s.start();
			System.out.println( "TCPSERVER START ON PORT: " + s.getPort() );
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	public void contextDestroyed(ServletContextEvent arg0) {
		try {
			s.stop();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}

請求json資料 java action 端
public void visitorjson(){
	String page = $.get("p");
	if($.empty(page)) page ="1";
	Map admin = (Map)$.session("admin");
	int s = $.time($.date());
	int e = s+24*60*60;
	String where=" and start_time>"+s+" and start_time<"+e;
	String start="select *";
	String cstart="select count(*) c";
	String sql=" from record where status=1 and admin_id="+admin.get("id")+" "+where;
	String limit =" order by start_time desc ";
	List<Map> list = new ArrayList<Map>();
	StringBuilder count = new StringBuilder("0");
	$.dbcp().query(start+sql+limit,list).count(cstart+sql,count).close();
	$.json("status",1).json("list",list).json("count",count).out();
}
查詢list 和 共多少條 ,然後返回json。是不是很優雅~~
$.dbcp().query(sql1,list).count(sql2,count).close();
$.json("status",1).json("list",list).json("count",count).out();