怎么在java中使用WebSocket实现一个聊天消息推送功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
十年的密云网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。网络营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整密云建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联从事“密云网站设计”,“密云网站推广”以来,每个客户项目都认真落实执行。
环境:
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 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); } /** * 消息发送触发方法 * @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+"/"; %>测试 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:
Java可以用来干什么
Java主要应用于:1. web开发;2. Android开发;3. 客户端开发;4. 网页开发;5. 企业级应用开发;6. Java大数据开发;7.游戏开发等。
看完上述内容,你们掌握怎么在java中使用WebSocket实现一个聊天消息推送功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
当前名称:怎么在java中使用WebSocket实现一个聊天消息推送功能
当前URL:http://scpingwu.com/article/ijpiod.html