運行環境:jdk8 tomcat8 無須其餘jar包。 package com.reach.socketController; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CopyOnWriteArraySet; import javax.annotation.Resource; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value ="/newwebsocket/{userId}") public class Webcomment { @Resource private Webcomment webcomment; //靜態變量,用來記錄當前在線鏈接數。應該把它設計成線程安全的。 private static int onlineCount = 0; //concurrent包的線程安全Set,用來存放每一個客戶端對應的MyWebSocket對象。若要實現服務端與單一客戶端通訊的話,能夠使用Map來存放,其中Key能夠爲用戶標識 private static CopyOnWriteArraySet<Webcomment> webSocketSet = new CopyOnWriteArraySet<Webcomment>(); //線程安全的Map private static ConcurrentHashMap<String,Session> webSocketMap = new ConcurrentHashMap<String,Session>();//創建鏈接的方法 @OnOpen public void onOpen(Session session,@PathParam("userId")String userId){ /*獲取從/websocket開始的整條連接,用於獲取userId?***=***的參數 String uri = session.getRequestURI().toString();*/ webSocketMap.put(userId, session); addOnlineCount(); //在線數加 System.out.println(userId+"進入聊天室"); System.out.println("有新鏈接加入!當前在線人數爲" + getOnlineCount()); } /** * 鏈接關閉調用的方法 */ @OnClose public void onClose(Session session){ Map<String, String> map = session.getPathParameters(); webSocketMap.remove(map.get("userId")); //從set中刪除 for(String user:webSocketMap.keySet()){ System.out.println(user); } subOnlineCount(); //在線數減 System.out.println("有一鏈接關閉!當前在線人數爲" + getOnlineCount()); } /** * 收到客戶端消息後調用的方法 * @param message 客戶端發送過來的消息 * @param session 可選的參數 */ @OnMessage public void onMessage(String message, Session session) { System.out.println("來自客戶端的消息:" + message); //獲取用戶ID Map<String, String> map = session.getPathParameters(); String userId = map.get("userId"); for(String user:webSocketMap.keySet()){ try { sendMessage(user+"你好,我是"+userId+" "+message,webSocketMap.get(user)); } catch (IOException e) { e.printStackTrace(); } } } /** * 發生錯誤時調用 * @param session * @param error */ @OnError public void onError(Session session, Throwable error){ System.out.println("發生錯誤"); error.printStackTrace(); } public void sendMessage(String message,Session session) throws IOException{ if(session.isOpen()){ session.getAsyncRemote().sendText(message); } //this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { Webcomment.onlineCount++; } public static synchronized void subOnlineCount() { Webcomment.onlineCount--; } }
html代碼,能夠單獨創建html,無須放在項目中javascript
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> new document </title> <meta name="generator" content="editplus" /> <meta name="author" content="" /> <meta name="keywords" content="" /> <meta name="description" content="" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="jquery-1.8.3.min.js" type="text/javascript"></script> </head> <body> <center> Welcome<br/><input id="text" type="text"/> <button onclick="send()">發送消息</button> <hr/> <button onclick="closeWebSocket()">關閉WebSocket鏈接</button> <hr/> <div id="message"></div> </body> <script type="text/javascript"> var websocket = null; //判斷當前瀏覽器是否支持WebSocket if ('WebSocket' in window) { alert('當前瀏覽器支持 websocket'); websocket = new WebSocket("ws://localhost:8080/Y-websocket/newwebsocket/234"); } else { alert('當前瀏覽器 Not support websocket') } //鏈接發生錯誤的回調方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket鏈接發生錯誤"); }; //鏈接成功創建的回調方法 websocket.onopen = function () { setMessageInnerHTML("WebSocket鏈接成功"); } //接收到消息的回調方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //鏈接關閉的回調方法 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(); } //發送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); } </script> </html>
友情提示: 向客戶端發送信息 sendText()是用來傳輸字符串的,有一個sendObject()方法能夠經過轉碼器發送javabean。 html
可是這裏咱們不推薦,由於很是麻煩。最簡單的辦法,就是把要發送的bean轉成json字符串。 bean轉jsonjava
而後在頁面將接收的json字符串轉成json:JSON.parse(event.data)jquery