通用的websocket模板代码
生活随笔
收集整理的這篇文章主要介紹了
通用的websocket模板代码
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
web聊天室后端代碼模板:
package com.jsx.chat;import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; 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.PathParam; import javax.websocket.server.ServerEndpoint;import net.sf.json.JSONObject;@ServerEndpoint("/websocket/{userId}") public class ChatServer {private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // 日期格式化//靜態(tài)變量,用來記錄當前在線連接數(shù)。應(yīng)該把它設(shè)計成線程安全的。private static int onlineCount = 0;//concurrent包的線程安全Set,用來存放每個客戶端對應(yīng)的MyWebSocket對象。若要實現(xiàn)服務(wù)端與單一客戶端通信的話,可以使用Map來存放,其中Key可以為用戶標識private static CopyOnWriteArraySet<ChatServer> webSocketSet = new CopyOnWriteArraySet<ChatServer>();//與某個客戶端的連接會話,需要通過它來給客戶端發(fā)送數(shù)據(jù)private Session session;private String userId;//----------單聊---------用戶id和websocket的session綁定的路由表//@SuppressWarnings("rawtypes")//private static Map routeTable = new HashMap<>();/*** 連接建立成功調(diào)用的方法* @param session 可選的參數(shù)。session為與某個客戶端的連接會話,需要通過它來給客戶端發(fā)送數(shù)據(jù)*/@OnOpenpublic void open(@PathParam("userId")String userIds,Session session) {// 添加初始化操作System.out.println("---初始化----userId:"+userIds);this.session = session;//獲取當前登錄用戶的idthis.userId = userIds;webSocketSet.add(this); //加入set中addOnlineCount(); //在線數(shù)加1System.out.println("有新連接加入!當前在線人數(shù)為" + getOnlineCount());//---------單聊-----------將用戶id和session綁定到路由表//綁定之后就可以在其它地方根據(jù)id來獲取session,這時兩個用戶私聊就可以實現(xiàn)了//routeTable.put(userId, session);}/*** 接受客戶端的消息,并把消息發(fā)送給所有連接的會話* @param message 客戶端發(fā)來的消息* @param session 客戶端的會話*/@OnMessagepublic void getMessage(String message, Session session1) {// 把客戶端的消息解析為JSON對象JSONObject jsonObject = JSONObject.fromObject(message);// 在消息中添加發(fā)送日期jsonObject.put("date", DATE_FORMAT.format(new Date()));// -----------------------把消息發(fā)送給所有連接的會話--------------------------------System.out.println("來自客戶端的消息"+this.userId+":" + message);for(ChatServer item: webSocketSet){try {//當前用戶右側(cè)顯示,非本用戶左側(cè)顯示if(this.userId.equals(item.userId)){jsonObject.put("isSelf", true);}else{jsonObject.put("isSelf", false);}// 發(fā)送JSON格式的消息item.sendMessage(jsonObject.toString());} catch (IOException e) {e.printStackTrace();continue;}}//--------------群發(fā)2------------------- // for (Session sess : session.getOpenSessions()) { // if (sess.isOpen()) // sess.getBasicRemote().sendText(msg); // }}@OnClosepublic void close() {// 添加關(guān)閉會話時的操作webSocketSet.remove(this); //從set中刪除subOnlineCount(); //在線數(shù)減1System.out.println("有一連接關(guān)閉!當前在線人數(shù)為" + getOnlineCount());}@OnErrorpublic void error(Throwable t) {// 添加處理錯誤的操作System.out.println("發(fā)生錯誤");t.printStackTrace();}/*** 這個方法與上面幾個方法不一樣。沒有用注解,是根據(jù)自己需要添加的方法。* @param message json消息* @throws IOException*/public synchronized void sendMessage(String message) throws IOException{this.session.getAsyncRemote().sendText(message);//非阻塞式的}public static synchronized int getOnlineCount() {return onlineCount;}public static synchronized void addOnlineCount() {ChatServer.onlineCount++;}public static synchronized void subOnlineCount() {ChatServer.onlineCount--;}}前端部分:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <title>即時群聊</title> <meta name="renderer" content="webkit"> <meta http-equiv="Cache-Control" content="no-siteapp" /> <link rel="alternate icon" href="assets/i/favicon.ico"> <link rel="stylesheet" href="assets/css/amazeui.min.css"> <link rel="stylesheet" href="assets/css/app.css"> <link href="umeditor/themes/default/css/umeditor.css" rel="stylesheet"> <style> .title {text-align: center; } .chat-content-container {height: 29rem;overflow-y: scroll;border: 1px solid silver; } </style> </head> <body><!-- 標題 --><div class="title"><div class="am-g am-g-fixed"><div class="am-u-sm-12"><h1 class="am-text-primary">群聊</h1></div></div></div><!-- 聊天內(nèi)容框開始 --><div class="chat-content"><div class="am-g am-g-fixed chat-content-container"><div class="am-u-sm-12"><ul id="message-list" class="am-comments-list am-comments-list-flip"></ul></div></div></div><!-- 聊天內(nèi)容框結(jié)束 --><div class="message-input am-margin-top"><!-- 輸入內(nèi)容框開始 --><div class="am-g am-g-fixed"><div class="am-u-sm-12"><form class="am-form"><div class="am-form-group"><script type="text/plain" id="myEditor" style="width: 100%;height: 8rem;"></script></div></form></div></div><!-- 輸入昵稱框開始 --><div class="am-g am-g-fixed am-margin-top"><div class="am-u-sm-6"><div id="message-input-nickname" class="am-input-group am-input-group-primary"><span class="am-input-group-label"><i class="am-icon-user"></i></span><input id="nickname" type="text" class="am-form-field" placeholder="Please enter nickname"/></div></div><div class="am-u-sm-6"><button id="send" type="button" class="am-btn am-btn-primary"><i class="am-icon-send"></i>發(fā)送</button></div></div></div><script src="assets/js/jquery.min.js"></script><script charset="utf-8" src="umeditor/umeditor.config.js"></script><script charset="utf-8" src="umeditor/umeditor.min.js"></script><script src="umeditor/lang/zh-cn/zh-cn.js"></script><script>$(function() {//隨機方法 生成id模擬用戶function rand(num){return parseInt(Math.random()*1000000+1);}// 初始化消息輸入框var um = UM.getEditor('myEditor');// 使昵稱框獲取焦點$('#nickname')[0].focus();// 新建WebSocket對象,最后的/WebSocket跟服務(wù)器端的@ServerEndpoint("/websocket")對應(yīng)//var socket = new WebSocket('ws://${pageContext.request.getServerName()}:${pageContext.request.getServerPort()}${pageContext.request.contextPath}/websocket');//var socket = new WebSocket("ws://localhost:8080/Chat/websocket");var target = "ws://"+window.location.host+"/Chat/websocket"+"/"+rand();//alert(target);var socket = new WebSocket(target);// 處理服務(wù)器端發(fā)送的數(shù)據(jù)socket.onmessage = function(event) {addMessage(event.data);};// 點擊Send按鈕時的操作$('#send').on('click', function() {var nickname = $('#nickname').val();//alert(um.getContent()); //內(nèi)容//alert(nickname); //昵稱if (!um.hasContents()) { // 判斷消息輸入框是否為空// 消息輸入框獲取焦點um.focus();// 添加抖動效果$('.edui-container').addClass('am-animation-shake');setTimeout("$('.edui-container').removeClass('am-animation-shake')", 1000);} else if (nickname == '') { // 判斷昵稱框是否為空//昵稱框獲取焦點$('#nickname')[0].focus();// 添加抖動效果$('#message-input-nickname').addClass('am-animation-shake');setTimeout("$('#message-input-nickname').removeClass('am-animation-shake')", 1000);} else {// 發(fā)送消息socket.send(JSON.stringify({content : um.getContent(),nickname : nickname}));// 清空消息輸入框um.setContent('');// 消息輸入框獲取焦點um.focus();}});// 把消息添加到聊天內(nèi)容中function addMessage(message) {message = JSON.parse(message);var messageItem = '<li class="am-comment '+ (message.isSelf ? 'am-comment-flip' : 'am-comment')+ '">'+ '<a href="javascript:void(0)" ><img src="assets/images/'+ (message.isSelf ? 'self.jpg' : 'others.jpg')+ '" alt="" class="am-comment-avatar" width="48" height="48"/></a>'+ '<div class="am-comment-main"><header class="am-comment-hd"><div class="am-comment-meta">'+ '<a href="javascript:void(0)" class="am-comment-author">'+ message.nickname + '</a> <time>' + message.date+ '</time></div></header>'+ '<div class="am-comment-bd">' + message.content+ '</div></div></li>';$(messageItem).appendTo('#message-list');// 把滾動條滾動到底部$(".chat-content-container").scrollTop($(".chat-content-container")[0].scrollHeight);}});</script></body> </html>總結(jié)
以上是生活随笔為你收集整理的通用的websocket模板代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【预留】Apache Doris 0.1
- 下一篇: java文件重命名有趣实验