怎么在java中使用WebSocket實(shí)現(xiàn)一個(gè)聊天消息推送功能?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
十年的密云網(wǎng)站建設(shè)經(jīng)驗(yàn),針對(duì)設(shè)計(jì)、前端、開發(fā)、售后、文案、推廣等六對(duì)一服務(wù),響應(yīng)快,48小時(shí)及時(shí)工作處理。網(wǎng)絡(luò)營銷推廣的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動(dòng)調(diào)整密云建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計(jì),從而大程度地提升瀏覽體驗(yàn)。創(chuàng)新互聯(lián)從事“密云網(wǎng)站設(shè)計(jì)”,“密云網(wǎng)站推廣”以來,每個(gè)客戶項(xiàng)目都認(rèn)真落實(shí)執(zhí)行。
環(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 Mapconnections = new HashMap (); 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()); } }
頁面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>測試 Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable Javascript and reload this page!
可指定發(fā)送給某個(gè)用戶,也可全部發(fā)送,詳情見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:
Java主要應(yīng)用于:1. web開發(fā);2. Android開發(fā);3. 客戶端開發(fā);4. 網(wǎng)頁開發(fā);5. 企業(yè)級(jí)應(yīng)用開發(fā);6. Java大數(shù)據(jù)開發(fā);7.游戲開發(fā)等。
看完上述內(nèi)容,你們掌握怎么在java中使用WebSocket實(shí)現(xiàn)一個(gè)聊天消息推送功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!