c语言sscanf函数的用法是什么
281
2022-12-17
使用springboot整合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
其中重点就是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小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~