加一个这个就行了,其他别乱加
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
package fig;import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;/*** 开启WebSocket支持* @author gxy* 2018年11月16日* my-work* success when you begin*/
@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}
package fig;import java.io.IOException;
import urrent.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.PathParam;
import javax.websocket.server.ServerEndpoint;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;/*** websocket基础类* @author gxy* 2018年11月16日* my-work* success when you begin*/
@ServerEndpoint(value="/mySocket/{userid}")
@Component
public class MyWebSocket {private static final Logger log = Logger(MyWebSocket.class);//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。private static int onlineCount = 0;//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();//与某个客户端的连接会话,需要通过它来给客户端发送数据private Session session;//接收sidprivate String sid="";/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session,@PathParam("userid") String sid) {this.session = session;webSocketSet.add(this); //加入set中addOnlineCount(); //在线数加1log.info("有新连接加入!当前在线人数为" + getOnlineCount());this.sid = sid;try {sendMessage("已有连接人数:"+getOnlineCount()+",连接人:"+sid);} catch (IOException e) {e.printStackTrace();log.info("IO异常");}}/*** 连接关闭调用的方法*/@OnClosepublic void onClose() {ve(this); //从set中删除subOnlineCount(); //在线数减1log.info("有一连接关闭!当前在线人数为" + getOnlineCount());}/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message, Session session) {log.info("来自客户端的消息:" + message);//群发消息for (MyWebSocket item : webSocketSet) {try {item.sendMessage(message);} catch (IOException e) {e.printStackTrace();}}}/*** 发生错误时调用*/@OnErrorpublic void onError(Session session, Throwable error) {log.info("发生错误");error.printStackTrace();}public void sendMessage(String message) throws IOException {BasicRemote().sendText(message);//AsyncRemote().sendText(message);}/*** 群发自定义消息* */public static void sendInfoAll(String message) throws IOException {for (MyWebSocket item : webSocketSet) {try {item.sendMessage(message);} catch (IOException e) {continue;}}}public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {log.info("推送消息到窗口"+sid+",推送内容:"+message);for (MyWebSocket item : webSocketSet) {try {//这里可以设定只推送给这个sid的,为null则全部推送if(sid==null) {item.sendMessage(message);}else if(item.sid.equals(sid)){item.sendMessage(message);}} catch (IOException e) {continue;}}}public static synchronized int getOnlineCount() {return onlineCount;}public static synchronized void addOnlineCount() {lineCount++;}public static synchronized void subOnlineCount() {lineCount--;}}
指定推送的控制器
package ller;import java.io.IOException;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 fig.MyWebSocket;
import work.util.AjaxReturnVO;/*** websocket消息推送* @author gxy* 2018年11月16日* my-work* success when you begin*/
@Controller
@RequestMapping(value="/pm")
public class PushMessageController {@GetMapping(value="/personalpage/{person}")public ModelAndView gotoPMPage(@PathVariable String person) {ModelAndView mav = new ModelAndView("/wbs/person");mav.addObject("cid", person);return mav;}//推送数据接口@ResponseBody@RequestMapping("/push/{cid}")public AjaxReturnVO pushToWeb(@PathVariable String cid,String message) { try {MyWebSocket.sendInfo(message,cid);} catch (IOException e) {e.printStackTrace();return AjaxReturnVO.Message());} return AjaxReturnVO.ok(cid);} }
页面
<!DOCTYPE html>
<html xmlns:th="" >
<head>
<meta charset="UTF-8">
<title>push message</title>
</head>
<body>it's <span th:text="${cid}" id="userId"></span> page,message is :<br/>
<div id="message">
</div>
</body>
<script type="text/javascript" th:src="@{/js/jquery-3.1.0.min.js}"></script>
<script type="text/javascript">var websocket = null;//判断当前浏览器是否支持WebSocketif('WebSocket' in window){websocket = new WebSocket("ws://localhost:68/mySocket/"+$('#userId').text());}else{alert('浏览器不支持接收后台推送')}//连接发生错误的回调方法r = function(){setMessageInnerHTML("error");};//连接成功建立的回调方法pen = function(event){setMessageInnerHTML("open");}//接收到消息的回调方法ssage = function(event){setMessageInnerHTML(event.data);}//连接关闭的回调方法lose = function(){setMessageInnerHTML("close");}//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。beforeunload = function(){websocket.close();}//将消息显示在网页上function setMessageInnerHTML(innerHTML){ElementById('message').innerHTML += innerHTML + '<br/>';}//关闭连接function closeWebSocket(){websocket.close();}//发送消息function send(){var message = ElementById('text').value;websocket.send(message);}
</script>
</html>
感谢:Moshow郑锴
本文发布于:2024-01-28 06:44:32,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063954785549.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |