websocket + showNotification

xiaoxiao2021-02-28  79

该文章简单使用了websocket和showNotification,并使用layer进行弹窗提示。 (该笔记用作个人笔记)罒ω罒大神请绕路 话不多说,直接上图(◕ᴗ◕✿): 当浏览器失去焦点时,消息将会在右下角推送(即:浏览器最小化时),现在是否看到右下角有推送(◕ᴗ◕✿)

浏览器不支持websocket时,将会在浏览器中间提示(◕ᴗ◕✿) 现在,图示已经完全显示了,感兴趣的童鞋可以继续往下码代码了(¬_¬)瞄

jsp文件

jsp代码以及注释,例如:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!doctype html> <html> <head> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <c:set var="ctx" value="${pageContext.request.contextPath}" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="${ctx}/js/layer/jquery-1.8.3.js"></script> <script type="text/javascript" src="${ctx}/js/layer/layer.js"></script> <link href="${ctx}/js/layer/jquery.treeview.css" type="text/css" rel="stylesheet" /> <title>websocket</title> </head> <body> Welcome<br/> <input id="text" type="text"/> <button onclick="send()">发送消息</button> <hr/> <div id="message"></div> <script type="text/javascript"> var websocket = null; var tification = false; //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { //ws://localhost:8080/websocket/websocket websocket = new WebSocket("ws://"+getPath()+"/websocket"); //连接发生错误的回调方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket连接发生错误"); }; //连接成功建立的回调方法 websocket.onopen = function () { setMessageInnerHTML("WebSocket连接成功"); } //接收到消息的回调方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket连接关闭"); } } else { layer.msg('浏览器不支持WebSocket,为了体验更好的效果,请使用谷歌、火狐、IE10等高版本浏览器', {time:0}); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { closeWebSocket(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; //当前窗口得到焦点 window.onfocus = function() { tification = false; }; //当前窗口失去焦点 window.onblur = function() { tification = true; }; if(tification){ showNotification(innerHTML) ; } } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } //发送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); } function showNotification (message) { window.Notification.permission = "granted"; if (window.Notification){ if (window.Notification.permission == "granted") { var notification = new Notification('通知消息', { body: message, icon: "http://"+getPath()+"/Images/xjj.jpg" }); setTimeout(function(){notification.close();},5000); } else { window.Notification.requestPermission(); } }else alert('你的浏览器不支持此消息提示功能,请使用chrome内核的浏览器!'); }; function getPath() { //获取当前网址,如: http://localhost:8080/websocket/index.jsp var curWwwPath = window.document.location.href; //获取主机地址之后的目录,如: websocket/index.jsp var pathName = window.document.location.pathname; //获取主机地址,如: localhost:8080 var hostport=document.location.host; //获取带"/"的项目名,如:/websocket var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1); return (hostport + projectName); } </script> </body> </html>

java文件

java代码以及注释:

package com.websocket.chat; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; 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.ServerEndpoint; //该注释表明访问路径,服务地址为ws://localhost:port/projectName/websocket @ServerEndpoint("/websocket") public class WebSocketListen { // 记录当前在线连接数。。 private static int onlineCount = 0; // 若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 private static CopyOnWriteArraySet<WebSocketListen> webSocketSet = new CopyOnWriteArraySet<WebSocketListen>(); //private static Map<String, WebSocketListen> webSocketSet = new HashMap<String, WebSocketListen>(); // 与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; /** * 连接建立成功调用的方法 * * @param session * 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 */ @OnOpen public void onOpen(Session session) { this.session = session; String id = session.getId()+"name"; // webSocketSet.put(session.getId()+"name" , this); webSocketSet.add(this);// 加入setaddOnlineCount(); // 在线数加1 // Set<String> A = getOnlineUser(); System.out.println("有新连接加入!当前在线人数为" + getOnlineCount()); } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); // 从set中删除 subOnlineCount(); // 在线数减1 System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * * @param message * 客户端发送过来的消息 * @param session * 可选的参数 */ @OnMessage public void onMessage(String message, Session session) { System.out.println("来自客户端的消息:" + message); if("".equals(message)){ message="妈的智障"; } // 群发消息 for (WebSocketListen item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); continue; } } //给user为2的推送消息 /* for(String key : webSocketSet.keySet()){ if(key.equals("2")){ try { webSocketSet.get(key).sendMessage(message); } catch (IOException e) { e.printStackTrace(); continue; } } }*/ } /** * 发生错误时调用 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { System.out.println("发生错误"); error.printStackTrace(); } /** * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。 * * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { //this.session.getBasicRemote().sendText(message); this.session.getAsyncRemote().sendText(message); } /** * 返回在线人数 * @author lhl * @date 2017-5-5下午6:13:24 * @return */ public static synchronized int getOnlineCount() { return onlineCount; } /** * 在线人数+1 * @author lhl * @date 2017-5-5下午6:12:21 */ public static synchronized void addOnlineCount() { WebSocketListen.onlineCount++; } /** * 在线人数-1 * @author lhl * @date 2017-5-5下午6:12:39 */ public static synchronized void subOnlineCount() { WebSocketListen.onlineCount--; } /** * 获取在线用户 * @author lhl * @date 2017-5-5下午6:12:54 * @return */ /*public static Set<String> getOnlineUser() { return webSocketSet.keySet(); } */ }

辣么,现在就大功告成了,鄙人比较懒,所以估计能耐心看完的不多(╥╯^╰╥),不过耐心看完的相信一定会有收获的! java文件中的注释可以删掉也可以放开,注释掉与其冲突的代码,是用来实现单对单的通信。

转载请注明原文地址: https://www.6miu.com/read-58867.html

最新回复(0)