websocket實現數據庫更新時前端頁面實時刷新


                                            websocket實現數據庫更新時前端頁面實時刷新                    </a>
            </span>
        </h1>
    </div>
    <div class="article_manage clearfix">
    <div class="article_l">

</div>

        <div class="category_r">
                                        <label>
                <span onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_fenlei']);">javaweb<em></em>
                </span> 
            </label> 
                                    </div>
    </div>
            <div class="bog_copyright">
                </div>
    <div style="clear:both"></div><div style="border:solid 1px #ccc; background:#eee; float:left; min-width:200px;padding:4px 10px;"><p style="text-align:right;margin:0;"><span style="float:left;">目錄<a href="https://blog.csdn.net/VVVinegar/article/details/71706670" title="系統根據文章中H1到H6標簽自動生成文章目錄">(?)</a></span><a href="#" onclick="javascript:return openct(this);" title="展開">[+]</a></p><ol style="display:none;margin-left:14px;padding-left:14px;line-height:160%;"><li><a href="https://blog.csdn.net/VVVinegar/article/details/71706670#t0">userjsp</a></li><li><a href="https://blog.csdn.net/VVVinegar/article/details/71706670#t1">ManagerServletjava</a></li></ol></div><div style="clear:both"></div><div id="article_content" class="article_content csdn-tracking-statistics" data-pid="blog" data-mod="popu_307" data-dsm="post" style="overflow: hidden;">
                <div class="markdown_views">
            <p>如題,實現以上功能,我知道主要有兩大種思路:</p>
  1. 輪詢:輪詢的原理是隔一段時間向服務器發送一個請求,這里不累述。這里主要談一下第二種思路。
  2. websocket進行前后端通訊:websocket是html5的新協議,基於TCP,在一次握手后,建立http連接,實現客戶端與服務端全雙工通信。相比較輪詢機制,節約資源,不需要頻繁的請求。

下面通過最精簡的javaweb+mysql實例說明,只貼出關鍵代碼。(原碼放在github中,里面有本例需要的websocket-api.jar,.sql文件以及README.doc,方便理解本例)。


user.jsp:





<%@ page import="model.UserBean" %>
<%@ page import="java.util.List" %>
<%@ page import="fun.Client" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<table id="table" border="1">
<tr>
<th >id</th>
<th >name</th>
</tr>
<%
//的到數據庫信息,放在list中
Client client=new Client();
List<UserBean> list= client.list();
if(list != null){
for(UserBean user : list){
%>

<tr >
<td ><%=user.getId()%></td>
<td ><%=user.getName()%></td>
</tr>
<%
}
}
%>

</table>
<div id="message"></div>

<script>
var websocket = null;
//判斷當前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
//建立連接,這里的/websocket ,是ManagerServlet中開頭注解中的那個值
websocket = new WebSocket("ws://localhost:8080/websocket");
}
else {
alert('當前瀏覽器 Not support websocket')
}
//連接發生錯誤的回調方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket連接發生錯誤");
};
//連接成功建立的回調方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket連接成功");
}
//接收到消息的回調方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
if(event.data=="1"){
location.reload();
}
}
//連接關閉的回調方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket連接關閉");
}
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function () {
closeWebSocket();
}
//將消息顯示在網頁上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
</script>
</body>
</html>

前面插入的java代碼得到數據庫中的信息,后面的js代碼實現websocket通訊。


ManagerServlet.java:

package fun;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.concurrent.CopyOnWriteArraySet;

/**
* 這個類即實現了進行數據庫操作的Servlet類,又實現了Websocket的功能.
*/


//該注解用來指定一個URI,客戶端可以通過這個URI來連接到WebSocket,類似Servlet的注解mapping;
// servlet的注冊放在了web.xml中。
@ServerEndpoint(value = "/websocket")
public class ManagerServlet extends HttpServlet {
//concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。若要實現服務端與單一客戶端通信的話,可以使用Map來存放,其中Key可以為用戶標識
private static CopyOnWriteArraySet<ManagerServlet> webSocketSet = new CopyOnWriteArraySet<ManagerServlet>();
//這個session不是Httpsession,相當於用戶的唯一標識,用它進行與指定用戶通訊
private javax.websocket.Session session=null;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
String msg;
String name=request.getParameter("name");
//這里submit是數據庫操作的方法,如果插入數據成功,則發送更新信號
if(submit(name)){
//發送更新信號
sendMessage();
msg="ok!";
}else {
msg="error!";
}
response.sendRedirect("manager.jsp?msg="+msg);
}
public void doPost(HttpServletRequest request,HttpServletResponse reponse) throws ServletException, IOException {
doGet(request,reponse);
}
/**
* 向數據庫插入一個name
* @param name
* @return
*/

public boolean submit(String name){
DB db=new DB();
String sql="insert into users(name) values(?)";
try{
PreparedStatement pstmt=db.con.prepareStatement(sql);
pstmt.setString(1,name);
pstmt.executeUpdate();
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}finally {
db.close();
}
}

/**
* @OnOpen allows us to intercept the creation of a new session.
* The session class allows us to send data to the user.
* In the method onOpen, we'll let the user know that the handshake was
* successful.
* 建立websocket連接時調用
*/

@OnOpen
public void onOpen(Session session){
System.out.println("Session " + session.getId() + " has opened a connection");
try {
this.session=session;
webSocketSet.add(this); //加入set中
session.getBasicRemote().sendText("Connection Established");
} catch (IOException ex) {
ex.printStackTrace();
}
}

/**
* When a user sends a message to the server, this method will intercept the message
* and allow us to react to it. For now the message is read as a String.
* 接收到客戶端消息時使用,這個例子里沒用
*/

@OnMessage
public void onMessage(String message, Session session){
System.out.println("Message from " + session.getId() + ": " + message);
}

/**
* The user closes the connection.
*
* Note: you can't send messages to the client from this method
* 關閉連接時調用
*/

@OnClose
public void onClose(Session session){
webSocketSet.remove(this); //從set中刪除
System.out.println("Session " +session.getId()+" has closed!");
}

/**
* 注意: OnError() 只能出現一次. 其中的參數都是可選的。
* @param session
* @param t
*/

@OnError
public void onError(Session session, Throwable t) {
t.printStackTrace();
}

/**
* 這個方法與上面幾個方法不一樣。沒有用注解,是根據自己需要添加的方法。
* @throws IOException
* 發送自定義信號,“1”表示告訴前台,數據庫發生改變了,需要刷新
*/

public void sendMessage() throws IOException{
//群發消息
for(ManagerServlet item: webSocketSet){
try {
item.session.getBasicRemote().sendText("1");
} catch (IOException e) {
e.printStackTrace();
continue;
}
}

}
}

這個類首先繼承了HttpServlet,目的是接收表單數據完成數據庫的修改。其次,這個類實現了websocket的功能。在doGet()方法中,可以看到,一旦數據庫發生改變,就會向前台發送“1”,前台收到“1”后即可刷新頁面。

    <div style="clear:both; height:10px;"></div>
</div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM