使用springboot整合websocket实现群聊教程

目录

  • 先上效果图:
  • 先来准备工作导入依赖
  • 导入依赖后扫描启用
  • 接收前端传回数据
  • 其中重点就是4个注解
    • **@OnOpen,@OnClose,@OnMessage,@OnError**
  • 前端页面代码
    • 模板引擎代码如下
      • 最后效果图如下
        使用springboot整合websocket实现群聊教程
        文章图片


        先上效果图: 使用springboot整合websocket实现群聊教程
        文章图片

        相对来说更好看那么一点但是,实现代码都是一样的。

        先来准备工作导入依赖
        org.springframework.bootspring-boot-starter-websocket

        其实springboot已经内置了,直接在主函数启动就行。但我们这次就讲这个。

        导入依赖后扫描启用
        package com.nx.study.springstudy.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configurationpublic class WS {@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter(); }}

        **@ServerEndpoint("/websocket/{username}")**

        接收前端传回数据 @Component启用
        package com.nx.study.springstudy.bean; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import net.sf.json.JSONObject; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; @ServerEndpoint("/websocket/{username}")@Componentpublic class Myws {private static Map webSocketSet = new ConcurrentHashMap(); private static Map map = new HashMap(); private static List namelist = new ArrayList(); private static JSONObject jsonObject = new JSONObject(); private static JSONObject jsonObject2 = new JSONObject(); private static List nm_msg = new ArrayList(); private SocketMsg socketMsg; private Session session; private String name; @OnOpenpublic void onpen(Session session, @PathParam(value = "https://www.it610.com/article/username") String username){if(username == null){username = "游客"; }this.session = session; //this.name = "南" + getname(); this.name = username; webSocketSet.put(name, this); map.put(username, session); namelist.clear(); // 清空原来的信息setonlion(); jsonObject.put("onlinepp", namelist); String message = jsonObject.toString(); broadcast2(message); }@OnClosepublic void onclose(){webSocketSet.remove(this.name); // 移除对象namelist.clear(); setonlion(); jsonObject.clear(); jsonObject.put("onlinepp", namelist); String message = jsonObject.toString(); broadcast3(message); }@OnMessagepublic void onmessage(String message){nm_msg.clear(); jsonObject2.clear(); nm_msg.add(name); nm_msg.add(message); jsonObject2.put("chat", nm_msg); String message2 = jsonObject2.toString(); broadcast(message2); }@OnErrorpublic void onError(Session session, Throwable error) {System.out.println("发生错误"); error.printStackTrace(); }public void broadcast(String message){for (Map.Entry item : webSocketSet.entrySet()){item.getValue().session.getAsyncRemote().sendText(message); }}public void broadcast2(String message){for (Map.Entry item : webSocketSet.entrySet()){item.getValue().session.getAsyncRemote().sendText(message); }}public void broadcast3(String message){for (Map.Entry item : webSocketSet.entrySet()){if (!item.getKey().equals(name)){item.getValue().session.getAsyncRemote().sendText(message); }}}public void setonlion(){for (Map.Entry item : webSocketSet.entrySet()){namelist.add(item.getKey()); }}public String getname() {String linkNo = ""; // 用字符数组的方式随机String model = "小大天明画美丽豪子余多少浩然兄弟朋友美韵紫萱好人坏蛋误解不要停栖栖遑遑可"; char[] m = model.toCharArray(); for (int j = 0; j < 2; j++) {char c = m[(int) (Math.random() * 36)]; // 保证六位随机数之间没有重复的if (linkNo.contains(String.valueOf(c))) {j--; continue; }linkNo = linkNo + c; }return linkNo; }}


        其中重点就是4个注解 【使用springboot整合websocket实现群聊教程】
        **@OnOpen,@OnClose,@OnMessage,@OnError**
        • @OnOpen–>客户端打开链接时候触发执行
        • @OnClose–>客户端关闭链接触发执行
        • @OnMessage–>客户端发送信息触发执行
        • @OnError–>发送错误时候触发执行
        对象信息都储存在Session,可以仔细看看上面代码很好理解。
        我们只需要理解这4个注解的作用就可以!

        前端页面代码
        在线聊天室
        文明用语,快乐你我他群聊游客




        关于我们  |  找我合作
        赣ICP备2021004042号

        因为我这个是springboot项目

        模板引擎代码如下
        package com.nx.study.springstudy.controller; import com.nx.study.springstudy.bean.UserPostForm; import com.nx.study.springstudy.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; @Controllerpublic class WebSocketController {@Autowiredprivate UserService userService; @RequestMapping("/websocket")public String webSocket(Model model, HttpServletRequest request){HttpSession httpSession = request.getSession(); String username = (String) request.getSession().getAttribute("username"); String userpassword = (String) request.getSession().getAttribute("userpassword"); if (username != null){UserPostForm Springuser = userService.query(username,userpassword); model.addAttribute("Springuser", Springuser); return "index/webSocket"; }else {return "index/ZGZG"; }}}


        最后效果图如下 使用springboot整合websocket实现群聊教程
        文章图片

        使用springboot整合websocket实现群聊教程
        文章图片

        以上就是使用springboot整合websocket实现群聊教程的详细内容,更多关于springboot整合websocket实现群聊的资料请关注脚本之家其它相关文章!

          推荐阅读