websocket(二) websocket的简单实现,识别用户属性的群聊
没什么好说的,websocket实现非常简单,我们直接看代码。 运行环境:jdk8 tomcat8 无须其他jar包。 具体环境支持自己百度 package com.reach.socketController; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CopyOnWriteArraySet; import javax.annotation.Resource; 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; @ServerEndpoint(value ="/newwebsocket/{userId}") public class Webcomment { @Resource private Webcomment webcomment; //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 private static CopyOnWriteArraySet<Webcomment> webSocketSet = new CopyOnWriteArraySet<Webcomment>();
//线程安全的Map private static ConcurrentHashMap<String,Session> webSocketMap = new ConcurrentHashMap<String,Session>();//建立连接的方法 @OnOpen public void onOpen(Session session,@PathParam("userId")String userId){ /*获取从/websocket开始的整条链接,用于获取userId?***=***的参数 String uri = session.getRequestURI().toString();*/ webSocketMap.put(userId, session); addOnlineCount(); //在线数加 System.out.println(userId+"进入聊天室"); System.out.println("有新连接加入!当前在线人数为" + getOnlineCount()); } /** * 连接关闭调用的方法 */ @OnClose public void onClose(Session session){ Map<String, String> map = session.getPathParameters(); webSocketMap.remove(map.get("userId")); //从set中删除 for(String user:webSocketMap.keySet()){ System.out.println(user); } subOnlineCount(); //在线数减 System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * @param message 客户端发送过来的消息 * @param session 可选的参数 */ @OnMessage public void onMessage(String message, Session session) { System.out.println("来自客户端的消息:" + message); //获取用户ID Map<String, String> map = session.getPathParameters(); String userId = map.get("userId"); for(String user:webSocketMap.keySet()){ try { sendMessage(user+"你好,我是"+userId+" "+message,webSocketMap.get(user)); } catch (IOException e) { e.printStackTrace(); } } } /** * 发生错误时调用 * @param session * @param error */ @OnError public void onError(Session session, Throwable error){ System.out.println("发生错误"); error.printStackTrace(); } public void sendMessage(String message,Session session) throws IOException{ if(session.isOpen()){ session.getAsyncRemote().sendText(message);
} //this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { Webcomment.onlineCount++; } public static synchronized void subOnlineCount() { Webcomment.onlineCount--; } }
html代码,可以单独建立html,无须放在项目中
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> new document </title> <meta name="generator" content="editplus" /> <meta name="author" content="" /> <meta name="keywords" content="" /> <meta name="description" content="" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="jquery-1.8.3.min.js" type="text/javascript"></script> </head> <body> <center> Welcome<br/><input id="text" type="text"/> <button onclick="send()">发送消息</button> <hr/> <button onclick="closeWebSocket()">关闭WebSocket连接</button> <hr/> <div id="message"></div> </body> <script type="text/javascript"> var websocket = null; //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { alert('当前浏览器支持 websocket'); websocket = new WebSocket("ws://localhost:8080/Y-websocket/newwebsocket/234"); } else { alert('当前浏览器 Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket连接发生错误"); }; //连接成功建立的回调方法 websocket.onopen = function () { setMessageInnerHTML("WebSocket连接成功"); } //接收到消息的回调方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket连接关闭"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { closeWebSocket(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } //发送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); } </script> </html>
友情提示: 向客户端发送信息 sendText()是用来传输字符串的,有一个sendObject()方法可以通过转码器发送javabean。
但是这里我们不推荐,因为非常麻烦。最简单的办法,就是把要发送的bean转成json字符串。 bean转json
然后在页面将接收的json字符串转成json:JSON.parse(event.data)
当你看完这两篇文章,虽然不保证websocket理解透彻,但是结合业务来使用websocket已经不是难题了!websocket学习起来就是这么简单
分类:
websocket
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?