diff --git a/pom.xml b/pom.xml index 3728a99535d486cb4efb33f68bc70fa2f6c07c29..17c3b126f3659fd3b2b6d771b12eacd31509915c 100644 --- a/pom.xml +++ b/pom.xml @@ -221,6 +221,12 @@ spring-boot-starter-websocket 2.6.6 + + + org.springframework.boot + spring-boot-starter-thymeleaf + 3.1.2 + diff --git a/src/main/java/com/kwan/springbootkwan/SpringBootKwanApplication.java b/src/main/java/com/kwan/springbootkwan/SpringBootKwanApplication.java index 1aa0afa380c5fa9ab9c0a11f23f0049a9a15ed38..750966a282f5cfb5709a53357839d8e9ae564725 100644 --- a/src/main/java/com/kwan/springbootkwan/SpringBootKwanApplication.java +++ b/src/main/java/com/kwan/springbootkwan/SpringBootKwanApplication.java @@ -4,8 +4,10 @@ import org.springframework.batch.core.configuration.annotation.EnableBatchProces import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.socket.config.annotation.EnableWebSocket; import springfox.documentation.swagger2.annotations.EnableSwagger2; +@EnableWebSocket @EnableSwagger2 @EnableScheduling @EnableBatchProcessing diff --git a/src/main/java/com/kwan/springbootkwan/config/WebSocketConfig.java b/src/main/java/com/kwan/springbootkwan/config/WebSocketConfig.java index ee016f6362be75d95a36ee64cc41fa8d91cedfb1..7980fcfef0cdada7832fd40291ffcbae0abd8be2 100644 --- a/src/main/java/com/kwan/springbootkwan/config/WebSocketConfig.java +++ b/src/main/java/com/kwan/springbootkwan/config/WebSocketConfig.java @@ -4,7 +4,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; - /** * 开启websocket的支持 * @@ -12,6 +11,7 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; * @version : 2.2.0 * @date : 2023/8/26 16:45 */ + @Configuration public class WebSocketConfig { @Bean diff --git a/src/main/java/com/kwan/springbootkwan/controller/SystemController.java b/src/main/java/com/kwan/springbootkwan/controller/SystemController.java deleted file mode 100644 index 19506748b2ed7e13175dd07fff530a9c5d17ac94..0000000000000000000000000000000000000000 --- a/src/main/java/com/kwan/springbootkwan/controller/SystemController.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.kwan.springbootkwan.controller; - -import com.kwan.springbootkwan.service.WebSocketServer; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.servlet.ModelAndView; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -@Controller("web_Scoket_system") -@RequestMapping("/api/socket") -public class SystemController { - //页面请求 - @GetMapping("/index/{userId}") - public ModelAndView socket(@PathVariable String userId) { - ModelAndView mav = new ModelAndView("/socket1"); - mav.addObject("userId", userId); - return mav; - } - - //推送数据接口 - @ResponseBody - @RequestMapping("/socket/push/{cid}") - public Map pushToWeb(@PathVariable String cid, String message) { - Map result = new HashMap<>(); - try { - WebSocketServer.sendInfo(message, cid); - result.put("code", cid); - result.put("msg", message); - } catch (IOException e) { - e.printStackTrace(); - } - return result; - } -} diff --git a/src/main/java/com/kwan/springbootkwan/filter/TimeFilter.java b/src/main/java/com/kwan/springbootkwan/filter/TimeFilter.java index fd8064ed4fc9ab8bc8f5b45487ba79f8ac1103be..98dff4a99dabf9d75fd3e3116c76f6b35835d772 100644 --- a/src/main/java/com/kwan/springbootkwan/filter/TimeFilter.java +++ b/src/main/java/com/kwan/springbootkwan/filter/TimeFilter.java @@ -18,7 +18,7 @@ public class TimeFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - log.info("先执行:接口执行时间"); +// log.info("先执行:接口执行时间"); chain.doFilter(request, response); } } diff --git a/src/main/java/com/kwan/springbootkwan/service/WebSocketServer.java b/src/main/java/com/kwan/springbootkwan/service/WebSocketServer.java index fe8460813cf19787726ab5988bdef1c273c8299a..6c5d9a7a55f36d230bd544c8038210ee311355b5 100644 --- a/src/main/java/com/kwan/springbootkwan/service/WebSocketServer.java +++ b/src/main/java/com/kwan/springbootkwan/service/WebSocketServer.java @@ -1,6 +1,5 @@ package com.kwan.springbootkwan.service; -import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.websocket.OnClose; @@ -8,126 +7,72 @@ 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; import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; import java.util.concurrent.CopyOnWriteArraySet; @Component -@Slf4j -@ServerEndpoint(value = "/api/websocket/{sid}") +@ServerEndpoint("/websocket") public class WebSocketServer { - - //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 - private static int onlineCount = 0; - //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 - private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet<>(); - - //与某个客户端的连接会话,需要通过它来给客户端发送数据 + //准备一个内部安全的集合 存放所有用户的websocket服务 + private static CopyOnWriteArraySet wsset = new CopyOnWriteArraySet<>(); private Session session; - //接收sid - private String sid = ""; - - /** - * 连接建立成功调用的方法 - */ @OnOpen - public void onOpen(Session session, @PathParam("sid") String sid) { + public void opOpen(Session session) { this.session = session; - webSocketSet.add(this); //加入set中 - this.sid = sid; - addOnlineCount(); //在线数加1 - try { - sendMessage("conn_success"); - log.info("有新窗口开始监听:" + sid + ",当前在线人数为:" + getOnlineCount()); - } catch (IOException e) { - log.error("websocket IO Exception"); - } - } + //将自身填充到set集合中 这个集合是所有客户端websocket的集合 + + wsset.add(this); +// sendMsg(); - /** - * 连接关闭调用的方法 - */ - @OnClose - public void onClose() { - webSocketSet.remove(this); //从set中删除 - subOnlineCount(); //在线数减1 - //断开连接情况下,更新主板占用情况为释放 - log.info("释放的sid为:" + sid); - //这里写你 释放的时候,要处理的业务 - log.info("有一连接关闭!当前在线人数为" + getOnlineCount()); } - /** - * 收到客户端消息后调用的方法 - * - * @ Param message 客户端发送过来的消息 - */ - @OnMessage - public void onMessage(String message, Session session) { - log.info("收到来自窗口" + sid + "的信息:" + message); - //群发消息 - for (WebSocketServer item : webSocketSet) { - try { - item.sendMessage(message); - } catch (IOException e) { - e.printStackTrace(); - } - } + @OnClose + public void onClose() { + //将自己从set集合中删除 + wsset.remove(this); } - /** - * @ Param session - * @ Param error - */ @OnError public void onError(Session session, Throwable error) { - log.error("发生错误"); - error.printStackTrace(); + System.out.println(this + "发生错误了"); } - /** - * 实现服务器主动推送 - */ - public void sendMessage(String message) throws IOException { - this.session.getBasicRemote().sendText(message); + //客户端发来消息 + @OnMessage + public void onMessage(String clientMsg, Session session) { + System.out.println("来自客户端的信息+“。。。。。。。。。”===》" + clientMsg); + //每隔一秒给你推送一条当前时间信息 + sendAllClient(clientMsg); } - /** - * 群发自定义消息 - */ - public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException { - log.info("推送消息到窗口" + sid + ",推送内容:" + message); - - for (WebSocketServer item : webSocketSet) { - try { - //这里可以设定只推送给这个sid的,为null则全部推送 - if (sid == null) { -// item.sendMessage(message); - } else if (item.sid.equals(sid)) { - item.sendMessage(message); - } - } catch (IOException e) { - continue; + private void sendMsg() { + try { + while (true) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String time = sdf.format(new Date()); + //发送数据 + this.session.getBasicRemote().sendText(time); + Thread.sleep(1000); } + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); } } - public static synchronized int getOnlineCount() { - return onlineCount; - } - - public static synchronized void addOnlineCount() { - WebSocketServer.onlineCount++; - } - - public static synchronized void subOnlineCount() { - WebSocketServer.onlineCount--; - } - - public static CopyOnWriteArraySet getWebSocketSet() { - return webSocketSet; + private void sendAllClient(String msg) { + try { + for (WebSocketServer wss : wsset) { + wss.session.getBasicRemote().sendText(msg); + } + } catch (IOException e) { + e.printStackTrace(); + } } -} +} \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 4426832ed909a5be2a6ccef4e4b32644e042c1e0..0e5d39fd8b0c58eb45d13c5ef53da97d7e784cdd 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -1,5 +1,5 @@ server: - port: 8888 + port: 8080 servlet: encoding: force: true diff --git a/src/main/resources/index.html b/src/main/resources/index.html index 20f4396a4604f577c28698680d39f331cbc93af9..bea827c8bf37044ff5587e944e897963cf89d8fa 100644 --- a/src/main/resources/index.html +++ b/src/main/resources/index.html @@ -1,74 +1,36 @@ - + - - - Java后端WebSocket的Tomcat实现 - - -
-Welcome
- -
- -
-
- +
只是接受消息的地方
+ +
+ +
- - \ No newline at end of file + + diff --git a/src/main/resources/templates/socket1.html b/src/main/resources/templates/socket1.html new file mode 100644 index 0000000000000000000000000000000000000000..20f4396a4604f577c28698680d39f331cbc93af9 --- /dev/null +++ b/src/main/resources/templates/socket1.html @@ -0,0 +1,74 @@ + + + + + + Java后端WebSocket的Tomcat实现 + + + + +
+Welcome
+ +
+ +
+
+ + + + \ No newline at end of file