WebSocket 推送gps点 demo 点对点
//依赖:
<!--websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
//配置:
@Configuration
@EnableWebSocketMessageBroker
@Slf4j
public class WebSocketSimpleConfig implements WebSocketMessageBrokerConfigurer {
private RemoteTokenServices tokenService;
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new ChannelInterceptor() {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
// 判断是否首次连接请求
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
// String tokens = accessor.getFirstNativeHeader("Authorization");
// log.info("webSocket token is {}", tokens);
// if (StrUtil.isBlank(tokens)) {
// return null;
// }
// // 验证令牌信息
// OAuth2Authentication auth2Authentication = tokenService.loadAuthentication(tokens.split(" ")[1]);
// if (ObjectUtil.isNotNull(auth2Authentication)) {
// SecurityContextHolder.getContext().setAuthentication(auth2Authentication);
// accessor.setUser(() -> auth2Authentication.getName());
// return message;
// } else {
// return null;
// }
log.info("首次连接");
}
//不是首次连接,已经成功登陆
return message;
}
});
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
//前端需要订阅的组
config.enableSimpleBroker("/topic");
//头部
config.setApplicationDestinationPrefixes("/websocket");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//前端连接地址
registry.addEndpoint("/ws") .setAllowedOrigins("*").withSockJS();
}
@Controller
@AllArgsConstructor
@Slf4j
//@RequestMapping("/websocket")
@Api(value = "webSocket", tags = "实时更新GPS/Update GPS in real time")
public class WebSocketController {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
WebSocketCarDeviceService webSocketCarDeviceService;
@Autowired
WebSocketCarDeviceServiceImpl webSocketCarDeviceServiceImpl;
@GetMapping("/gps-html")
@Inner(value = false)
public ModelAndView gps() {
return new ModelAndView("websocket.html");
}
//前端连接的地址 /websocket/gps
@MessageMapping("/gps")
@GetMapping("/gps")
public void greeting(GpsMessage message) {
//根据车辆进行缓存到redis中 并且设置时间
redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY +
message.getLicCode(),message.getLicCode(),
SecurityConstants.CODE_TIME,TimeUnit.SECONDS);
//上下文引用数据传递
webSocketCarDeviceServiceImpl.setDate(message.getLicCode());
SimpMessagingTemplate simpMessagingTemplate = SpringContextHolder.getBean(SimpMessagingTemplate.class);
String latLon = webSocketCarDeviceService.queryGpsLatLonByLicCode(message.getLicCode());
//进行推送 根据车辆进行订阅这个组
simpMessagingTemplate.convertAndSend("/topic/greetings/" + message.getLicCode(),
new Greeting(latLon));
}
@OnClose()
public void onClose(){
System.out.println("进来");
}
//定时事实推送gps点
/**
* 由于定时任务无法带参 采用上下文进行引用 --this.date;
* 定时推送给前端gps点
*/
@Scheduled(cron = "0/10 * * * * ?")
public void greetings() {
String key = CacheConstants.DEFAULT_CODE_KEY + this.date;
redisTemplate.setKeySerializer(new StringRedisSerializer());
if (redisTemplate.hasKey(key)) {
Object licCode = redisTemplate.opsForValue().get(key);
if (!Objects.equals(licCode, null)) {
SimpMessagingTemplate simpMessagingTemplate = SpringContextHolder.getBean(SimpMessagingTemplate.class);
String latLon = this.queryGpsLatLonByLicCode(licCode.toString());
if (StringUtils.isNotEmpty(latLon)) {
//进行推送 根据车辆进行订阅这个组
simpMessagingTemplate.convertAndSend("/topic/greetings/" + this.date,
new Greeting(latLon));
}
}
}
}
/**
* 由于定时任务无法带参 采用上下文进行引用
* 上下文引用数据传递 传递的参数为车牌号
*/
private String date;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
前端
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>点对点</title>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">GPS点</h2></noscript>
<div id="main-content" class="container">
<div class="row">
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="connect">WebSocket connection:</label>
<button id="connect" class="btn btn-default" type="submit">Connect</button>
<button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
</button>
</div>
</form>
</div>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="name">What is your name?</label>
<input type="text" id="name" class="form-control" placeholder="Your name here...">
</div>
<button id="send" class="btn btn-default" type="submit">Send</button>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>Greetings</th>
</tr>
</thead>
<tbody id="greetings">
</tbody>
</table>
</div>
</div>
</div>
<script src="js/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var stompClient = null;
function connect() {
var socket = new SockJS('https://172.18.1.108:9999/websocket/ws');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
//A01是车牌号 用来订阅不同的组 这里根据用户输入车牌号进行订阅
stompClient.subscribe('/topic/greetings/A01', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function sendName() {
stompClient.send("/websocket/gps", {}, JSON.stringify({'licCode': $("#name").val()}));
}
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#greetings").html("");
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function showGreeting(message) {
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() {sendName(); });
});
</script>
</body>
</html>
改动来自 :https://blog.csdn.net/ApolloNing/article/details/111029320