<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>WebSocket示例</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="description" content="This is my page"> </head> <body> <button onclick="subOpen();">open</button><br/> <input type="text" name="msg" id="msg"><br/> <button onclick="send();">發送</button> <div id="div"></div> </body> <script type="text/javascript"> var ws; // 就是一個通訊管道 var target = "ws://localhost:8080/WebsocketTest/echo";//服務端的url,注意以ws開頭 function subOpen(){ //三個判斷用於獲取ws通訊管道(瀏覽器兼容) if('WebSocket' in window){ ws = new WebSocket(target); }else if('MozWebSocket' in window){ ws = new MozMozWebSocket(target); }else{ alert("WebSocket is not supported by this browse"); return; } //ws.onopen = function(){} 連接開啓會執行方法 //ws.onclose = function(){} 斷開鏈接會執行方法 //以上兩個實際用處並很少,主要是下面的 //服務器又信息返回就執行方法 ws.onmessage=function(event){ //服務端一返回內容,就把該內容放到div標籤當中 document.getElementById("div").innerHTML = event.data; //方便在控制檯查看返回內容的具體信息 console.info(event); }; }; function send(){ //點擊發送按鈕就把輸入框裏的內容發送給服務器,並把輸入框的內容清空 var msg = document.getElementById("msg").value; ws.send(msg); document.getElementById("msg").value = ""; }; </script> </html>
package Test; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.CloseReason; import javax.websocket.EndpointConfig; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; //註解規定了訪問的URL @ServerEndpoint("/echo") public class EchoSocket { /** * 客戶端有鏈接的時候就會調用這個方法 */ @OnOpen public void open(Session session, EndpointConfig config){ System.out.println(session.getId()+"#############"); } /** * 客戶端鏈接斷開就會調用此方法 */ @OnClose public void close(Session session,CloseReason reason){ System.out.println(session.getId() + "鏈接關閉了"); } /** * 接收到客戶端的信息 * @param msg * @param last */ @OnMessage public void message(Session session,boolean last,String msg){ System.out.println("客戶端說" + msg); try { session.getBasicRemote().sendText("ni hao too"); Thread.sleep(3000);//三秒後再發送一條信息,用於驗證是否實現數據實時更新 session.getBasicRemote().sendText("ni hao too twice"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** *錯誤監聽(當沒有關閉socket鏈接就關閉瀏覽器會異常) */ @OnError public void error(Session session, Throwable error){ String id = session.getId(); System.out.println("出錯的session的id是" + id); } public EchoSocket(){ System.out.println("Socket對象建立"); //經過對象的建立能夠知道不一樣socket之間的通訊不會共享成員變量 } }