java WebSocket實(shí)現(xiàn)聊天消息推送功能
本文實(shí)例為大家分享了java WebSocket實(shí)現(xiàn)聊天消息推送功能的具體代碼,供大家參考,具體內(nèi)容如下
環(huán)境:
JDK.1.7.0_51
apache-tomcat-7.0.53
java jar包:tomcat-coyote.jar、tomcat-juli.jar、websocket-api.jar
ChatAnnotation消息發(fā)送類:
import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; 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; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import com.util.HTMLFilter; /** * WebSocket 消息推送服務(wù)類 * @author 胡漢三 * * 2014-11-18 下午7:53:13 */ @ServerEndpoint(value = "/websocket/chat") public class ChatAnnotation { private static final Log log = LogFactory.getLog(ChatAnnotation.class); private static final String GUEST_PREFIX = "Guest"; private static final AtomicInteger connectionIds = new AtomicInteger(0); private static final Map<String,Object> connections = new HashMap<String,Object>(); private final String nickname; private Session session; public ChatAnnotation() { nickname = GUEST_PREFIX + connectionIds.getAndIncrement(); } @OnOpen public void start(Session session) { this.session = session; connections.put(nickname, this); String message = String.format("* %s %s", nickname, "has joined."); broadcast(message); } @OnClose public void end() { connections.remove(this); String message = String.format("* %s %s", nickname, "has disconnected."); broadcast(message); } /** * 消息發(fā)送觸發(fā)方法 * @param message */ @OnMessage public void incoming(String message) { // Never trust the client String filteredMessage = String.format("%s: %s", nickname, HTMLFilter.filter(message.toString())); broadcast(filteredMessage); } @OnError public void onError(Throwable t) throws Throwable { log.error("Chat Error: " + t.toString(), t); } /** * 消息發(fā)送方法 * @param msg */ private static void broadcast(String msg) { if(msg.indexOf("Guest0")!=-1){ sendUser(msg); } else{ sendAll(msg); } } /** * 向所有用戶發(fā)送 * @param msg */ public static void sendAll(String msg){ for (String key : connections.keySet()) { ChatAnnotation client = null ; try { client = (ChatAnnotation) connections.get(key); synchronized (client) { client.session.getBasicRemote().sendText(msg); } } catch (IOException e) { log.debug("Chat Error: Failed to send message to client", e); connections.remove(client); try { client.session.close(); } catch (IOException e1) { // Ignore } String message = String.format("* %s %s", client.nickname, "has been disconnected."); broadcast(message); } } } /** * 向指定用戶發(fā)送消息 * @param msg */ public static void sendUser(String msg){ ChatAnnotation c = (ChatAnnotation)connections.get("Guest0"); try { c.session.getBasicRemote().sendText(msg); } catch (IOException e) { log.debug("Chat Error: Failed to send message to client", e); connections.remove(c); try { c.session.close(); } catch (IOException e1) { // Ignore } String message = String.format("* %s %s", c.nickname, "has been disconnected."); broadcast(message); } } }
HTMLFilter工具類:
/** * HTML 工具類 * * @author 胡漢三 */ public final class HTMLFilter { public static String filter(String message) { if (message == null) return (null); char content[] = new char[message.length()]; message.getChars(0, message.length(), content, 0); StringBuilder result = new StringBuilder(content.length + 50); for (int i = 0; i < content.length; i++) { switch (content[i]) { case '<': result.append("<"); break; case '>': result.append(">"); break; case '&': result.append("&"); break; case '"': result.append("""); break; default: result.append(content[i]); } } return (result.toString()); } }
頁(yè)面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>測(cè)試</title> <style type="text/css"> input#chat { width: 410px } #console-container { width: 400px; } #console { border: 1px solid #CCCCCC; border-right-color: #999999; border-bottom-color: #999999; height: 170px; overflow-y: scroll; padding: 5px; width: 100%; } #console p { padding: 0; margin: 0; } </style> <script type="text/javascript"> var Chat = {}; Chat.socket = null; Chat.connect = (function(host) { if ('WebSocket' in window) { Chat.socket = new WebSocket(host); } else if ('MozWebSocket' in window) { Chat.socket = new MozWebSocket(host); } else { Console.log('Error: WebSocket is not supported by this browser.'); return; } Chat.socket.onopen = function () { Console.log('Info: WebSocket connection opened.'); document.getElementById('chat').onkeydown = function(event) { if (event.keyCode == 13) { Chat.sendMessage(); } }; }; Chat.socket.onclose = function () { document.getElementById('chat').onkeydown = null; Console.log('Info: WebSocket closed.'); }; Chat.socket.onmessage = function (message) { Console.log(message.data); }; }); Chat.initialize = function() { if (window.location.protocol == 'http:') { Chat.connect('ws://' + window.location.host + '/socket2/websocket/chat'); } else { Chat.connect('wss://' + window.location.host + '/socket2/websocket/chat'); } }; Chat.sendMessage = (function() { var message = document.getElementById('chat').value; if (message != '') { Chat.socket.send(message); document.getElementById('chat').value = ''; } }); var Console = {}; Console.log = (function(message) { var console = document.getElementById('console'); var p = document.createElement('p'); p.style.wordWrap = 'break-word'; p.innerHTML = message; console.appendChild(p); while (console.childNodes.length > 25) { console.removeChild(console.firstChild); } console.scrollTop = console.scrollHeight; }); Chat.initialize(); document.addEventListener("DOMContentLoaded", function() { // Remove elements with "noscript" class - <noscript> is not allowed in XHTML var noscripts = document.getElementsByClassName("noscript"); for (var i = 0; i < noscripts.length; i++) { noscripts[i].parentNode.removeChild(noscripts[i]); } }, false); </script> </head> <body> <div class="noscript"><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable Javascript and reload this page!</h2></div> <div> <p> <input type="text" placeholder="請(qǐng)輸入內(nèi)容" id="chat" /> </p> <div id="console-container"> <div id="console"/> </div> </div> </body> </html>
可指定發(fā)送給某個(gè)用戶,也可全部發(fā)送,詳情見(jiàn)ChatAnnotation類的broadcast方法。
程序發(fā)布時(shí)記得刪除tomcat-coyote.jar、tomcat-juli.jar、websocket-api.jar這三個(gè)jar包在啟動(dòng)Tomcat。
程序截圖,Guest0用戶發(fā)送信息的信息,在后臺(tái)進(jìn)行了判斷只發(fā)送給自己:
Guest1:
Guest2:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
淺談Servlet 實(shí)現(xiàn)網(wǎng)頁(yè)重定向的方法
本篇文章主要介紹了Servlet 實(shí)現(xiàn)重定向幾種方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08Java C++題解leetcode816模糊坐標(biāo)示例
這篇文章主要為大家介紹了Java C++題解leetcode816模糊坐標(biāo)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01InputStreamReader和BufferedReader用法及實(shí)例講解
這篇文章主要介紹了InputStreamReader和BufferedReader用法及實(shí)例講解的相關(guān)資料,需要的朋友可以參考下2015-12-12Springboot?配置SqlSessionFactory方式
這篇文章主要介紹了Springboot?配置SqlSessionFactory方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12swing jtextArea滾動(dòng)條和文字縮放效果
這篇文章主要為大家詳細(xì)介紹了swing jtextArea滾動(dòng)條和文字縮放效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12java實(shí)現(xiàn)zip,gzip,7z,zlib格式的壓縮打包
本文是利用Java原生類和apache的commons實(shí)現(xiàn)zip,gzip,7z,zlib的壓縮打包,如果你要是感興趣可以進(jìn)來(lái)了解一下。2016-10-10