标签:com thymeleaf btn java try star start pack 简单的
今天简单看了一下webscoket的相关内容,写了一个入门demo,简单记录一下。
服务端使用springboot来搭建,引入spring-boot-starter-websocket模块,以及web模块来做页面。页面使用简单的thymeleaf模板。
服务的配置websocket需要先定义WebSocketExporter的bean,使用默认的构造方法即可。
package com.chat.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
创建websocket服务主要需要处理创建连接、发送消息、断开连接、发生错误这几种情况的逻辑。
package com.chat.bean; import java.io.IOException; import java.util.HashMap; import java.util.Map; 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; import org.springframework.stereotype.Component; @ServerEndpoint(value="/sunSocket") @Component public class SunWebSocket { /** * 记录在线链接数 */ private static int onLineNum = 0; /** * concurrent包的线程安全set,存放每个客户端连接对应的webSocket对象。 */ private static CopyOnWriteArraySet<SunWebSocket> webSocketSet = new CopyOnWriteArraySet<>(); /** * 与某个客户端的会话,通过会话给客户端传递消息 */ private Session session; /** * 开启一个客户端对话连接 * @param session */ @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); addOnlineCount(); sendMsg("欢迎加入聊天室", session); } /** * 当连接断开时调用的方法 * @param session */ @OnClose public void onClose(Session session) { webSocketSet.remove(this); subOnlineCount(); System.out.println("有人走了"); } /** * 当有来自客户端的消息时 * @param msg * @param session */ @OnMessage public void onMessage(String msg,Session session) { Map<String, String> map = new HashMap<>(); map.put("ip",session.getId()); map.put("msg",msg); for (SunWebSocket sunWebSocket : webSocketSet) { try { sunWebSocket.session.getBasicRemote().sendText(session.getId() + ":" + msg); } catch (IOException e) { e.printStackTrace(); } } } @OnError public void onError(Session session,Throwable error) { try { session.getBasicRemote().sendText(error.getMessage()); } catch (IOException e) { error.printStackTrace(); e.printStackTrace(); } } public void sendMsg(String msg, Session session) { try { session.getBasicRemote().sendText(msg); } catch (IOException e) { e.printStackTrace(); } } public static synchronized int getOnlineCount() { return onLineNum; } public static synchronized void addOnlineCount() { onLineNum++; } public static synchronized void subOnlineCount() { onLineNum--; } }
启动springboot服务后台内容即完成。
demo的客户端使用html5的websocket来编写。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>在线聊天</title> <style type="text/css"> #msg-view{ height: 400px; overflow: scroll; } </style> </head> <body> <div id="msg-view"> </div> <div id="msg-input"> <input id="msg"/> <button id="sendBtn" onclick="sendMsg()">发送</button> </div> <script type="text/javascript"> var websocket = null; if(‘WebSocket‘ in window){ websocket = new WebSocket("ws://localhost:8080/sunSocket") } else{ alert(‘Not support websocket‘) } websocket.onmessage = function (event) { var data = event.data; if(typeof(data) == ‘string‘){ showMsg(data) }else{ showMsg(data.ip + ‘:‘ + data.msg) } } /* 页面关闭监听 */ window.onbeforeunload = function(){ websocket.close(); } /** * 错误情况 */ websocket.onerror = function () { showMsg(‘连接异常‘) } function sendMsg() { var msg = document.getElementById(‘msg‘).value; websocket.send(msg) } function showMsg(msg) { document.getElementById(‘msg-view‘).innerHTML += msg + ‘<br/>‘; } </script> </body> </html>
标签:com thymeleaf btn java try star start pack 简单的
原文地址:https://www.cnblogs.com/sunleaf/p/11082524.html