微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java WebSocket实现聊天消息推送功能

这篇文章主要为大家详细介绍了java WebSocket实现聊天消息推送功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了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 connections = 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); } /** * 消息发送触发方法 * @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 ': result.append(">"); break; case '&': result.append("&"); break; case '"': result.append("""); break; default: result.append(content[i]); } } return (result.toString()); } }

页面

测试

Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable Javascript and reload this page!

可指定发送给某个用户,也可全部发送,详情见Chatannotation类的broadcast方法

程序发布时记得删除tomcat-coyote.jar、tomcat-juli.jar、websocket-api.jar这三个jar包在启动Tomcat。

程序截图,Guest0用户发送信息的信息,在后台进行了判断只发送给自己:

Guest1:

Guest2:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐