標籤:
websocket是Html5的一個協議,也就是說距離我們2016年就幾年時間,其他原理我就不說了,直接講例子
一、準備材料:1、一個開發工具必須支援javaEE7的,原因是javaEE6或以下不支援websocket,我是使用的開發工具是myeclipse2015,這裡給各位百度雲端硬碟
連結: https://pan.baidu.com/s/1eS3DrPK 密碼: 4fe1,裡面有破解的工具,很方便
2、tomcat8.0以上、JDK7.0以上(這個也許就是websocket是近幾年的原因)
二、建立一個web項目,必須選擇JavaEE7.0以上(圖1-1)
圖1-1
三、
(1)、jsp代碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP ‘index.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <meta content="text/html";charset="utf-8"> <script src="<%=request.getContextPath()%>/js/jquery-2.1.4.min.js" ></script> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form> <h1>WebSocket送信執行個體</h1> <input type="text" id="message" disabled="disabled" required> <input type="button" onclick="echo()" disabled="disabled" value="提交"> </form> </body> <script> if (!window.WebSocket && window.MozWebSocket) window.WebSocket = window.MozWebSocket; if (!window.WebSocket) { alert("此瀏覽器不支援WebSocket"); } //建立WebSocket,location.host獲得主機名稱+連接埠號碼 var ws = new WebSocket("ws://" + location.host + "/websocket/websocket"); //串連建立後調用的函數 ws.onopen = function() { //將我們的form改變為可以輸入的形式 $("form *").attr("disabled", false); } //接受伺服器傳入的資料的處理 ws.onmessage = function(event) { alert(event.data); } //點擊提交按鈕後調用的參數 function echo() { ws.send($("#message").val()); }</script></html>
(2)、java代碼
package com;import java.io.IOException;import java.util.concurrent.CopyOnWriteArraySet;import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;@ServerEndpoint("/websocket") public class MyWebSocket { //靜態變數,用來記錄當前線上串連數。應該把它設計成安全執行緒的。 private static int onlineCount = 0; //concurrent包的安全執行緒Set,用來存放每個用戶端對應的MyWebSocket對象。若要實現服務端與單一用戶端通訊的話,可以使用Map來存放,其中Key可以為使用者標識 private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>(); //與某個用戶端的串連會話,需要通過它來給用戶端發送資料 private Session session; /** * 串連建立成功調用的方法 * @param session 可選的參數。session為與某個用戶端的串連會話,需要通過它來給用戶端發送資料 */ @OnOpen public void onOpen(Session session){ this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //線上數加1 System.out.println("有新串連加入!當前線上人數為" + getOnlineCount()); } /** * 串連關閉調用的方法 */ @OnClose public void onClose(){ webSocketSet.remove(this); //從set中刪除 subOnlineCount(); //線上數減1 System.out.println("有一串連關閉!當前線上人數為" + getOnlineCount()); } /** * 收到用戶端訊息後調用的方法 * @param message 用戶端發送過來的訊息 * @param session 可選的參數 */ @OnMessage public void onMessage(String message, Session session) { System.out.println("來自用戶端的訊息:" + message); //群發訊息 for(MyWebSocket item: webSocketSet){ try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); continue; } } } /** * 發生錯誤時調用 * @param session * @param error */ @OnError public void onError(Session session, Throwable error){ System.out.println("發生錯誤"); error.printStackTrace(); } /** * 這個方法與上面幾個方法不一樣。沒有用註解,是根據自己需要添加的方法。 * @param message * @throws IOException */ public void sendMessage(String message) throws IOException{ this.session.getBasicRemote().sendText(message); //this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { MyWebSocket.onlineCount++; } public static synchronized void subOnlineCount() { MyWebSocket.onlineCount--; } }
相信大家好好體會代碼,我也是花了一兩個鐘才做成這個例子的,然後就立刻給部落格友寫文章,喜歡和我交流可以加我的部落格園
Websocket簡單例子