java WebSocket实现聊天消息推送功能
程序员文章站
2023-12-20 19:41:04
本文实例为大家分享了java websocket实现聊天消息推送功能的具体代码,供大家参考,具体内容如下
环境:
jdk.1.7.0_51
apache-tomc...
本文实例为大家分享了java websocket实现聊天消息推送功能的具体代码,供大家参考,具体内容如下
环境:
jdk.1.7.0_51
apache-tomcat-7.0.53
java jar包:tomcat-coyote.jar、tomcat-juli.jar、websocket-api.jar
chatannotation消息发送类:
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 消息推送服务类 * @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); } /** * 消息发送触发方法 * @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); } /** * 消息发送方法 * @param msg */ private static void broadcast(string msg) { if(msg.indexof("guest0")!=-1){ senduser(msg); } else{ sendall(msg); } } /** * 向所有用户发送 * @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); } } } /** * 向指定用户发送消息 * @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+"/"; %> <?xml version="1.0" encoding="utf-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>测试</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="请输入内容" id="chat" /> </p> <div id="console-container"> <div id="console"/> </div> </div> </body> </html>
可指定发送给某个用户,也可全部发送,详情见chatannotation类的broadcast方法。
程序发布时记得删除tomcat-coyote.jar、tomcat-juli.jar、websocket-api.jar这三个jar包在启动tomcat。
程序截图,guest0用户发送信息的信息,在后台进行了判断只发送给自己:
guest1:
guest2:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。