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

网友投稿 281 2022-12-17

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

先上效果图:

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

我们先来准备工作导入依赖

org.springframework.boot spring-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 { @Bean public 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; @OnOpen public void onpen(Session session, @PathParam(value = "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); } @OnClose public void onclose(){ webSocketSet.remove(this.name); // 移除对象 namelist.clear(); setonlion(); jsonObject.clear(); jsonObject.put("onlinepp", namelist); String message = jsonObject.toString(); broadcast3(message); } @OnMessage public 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); } @OnError public 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个注解

**@OnOpen,@OnClose,@OnMessage,@OnError**

@OnOpen–>客户端打开链接时候触发执行

@OnClose–>客户端关闭链接触发执行

@OnMessage–>客户端发送信息触发执行

@OnError–>发送错误时候触发执行

对象信息都储存在Session,可以仔细看看上面代码很好理解。

我们只需要理解这4个注解的作用就可以!

前端页面来了代码如下

因为我这个是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 { @Autowired private 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实现群聊的资料请关注我们其它相关文章!

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot 利用RestTemplate http测试
下一篇:RestTemplate 401 获取错误信息的处理方案
相关文章

 发表评论

暂时没有评论,来抢沙发吧~