1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.配置文件
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
/***
* 注册 Stomp的端点 addEndpoint:添加STOMP协议的端点。提供WebSocket或SockJS客户端访问的地址
* 这里没有使用SockJS协议,因为该协议只支持文本消息,启用了WebSocket的访问地址
*
* @param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/message").setAllowedOrigins("*");
}
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
// 设置最大消息发送长度为5m
registry.setMessageSizeLimit(1024 * 1024 * 5);
registry.setSendBufferSizeLimit(1024 * 1024 * 5);
registry.setSendTimeLimit(2000);
}
/**
* 配置消息代理 启动Broker,消息的发送的地址符合配置的前缀来的消息才发送到这个broker
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");// 推送消息前缀
registry.setApplicationDestinationPrefixes("/topic");// 应用请求前缀
registry.setUserDestinationPrefix("/user");// 推送用户前缀
}
}
3.Controller 消息控制器
@Api(tags = "消息控制器")
@RestController
public class MessageController {
@Autowired
private IMessageService service;
/**
* 字节传输 接受前端传输过来的数据
* 有效载荷
*
* @throws Exception
*/
@MessageMapping("/server/byte")
public void subscribeByte(@Headers Map<String, Object> headers, String s) {
System.out.println(s);
service.subscribeByte(headers, s);
}
@Autowired
private SimpMessagingTemplate messagingTemplate;
/**
* 主动通过socket发数据给前端,模拟由硬件或算法调用该接口
*
* @param headers
* @param s
*/
@PostMapping("/server/aa")
public void subscribeByte1(@Headers Map<String, Object> headers, String s) {
//
new Thread(new Msg(s, messagingTemplate)).start();
// service.subscribeByte(headers, s);
}
/**
* 定义传输类
*/
public class Msg implements Runnable {
private String msg;
private SimpMessagingTemplate messagingTemplate;
public Msg(String msg, SimpMessagingTemplate messagingTemplate) {
this.msg = msg;
this.messagingTemplate = messagingTemplate;
}
@Override
public void run() {
this.messagingTemplate.convertAndSend("/topic/anquanmao", msg);
}
}
}
4.html 连接socket
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<body>
<h3>选择一张图片并通过websocket发送到后台</h3>
<input accept="image/*" type="text" id="file">
<br/>
<h3>后台会实时通过websocket把图片回传(可以把本页面打开两个以测试效果)</h3>
<div style="width: 800px; height: 600px;">
<img alt="" id="img" width="800" height="600" src=""/>
</div>
</body>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="js/stomp.js"></script>
<script type="text/javascript" src="js/websocket.js"></script>
<script type="text/javascript">
// !!!!不是原生的WebSoceket,使用的spring-boot-starter-websocket包,基于STOMP协议的WebSocket
//websocket链接成功后回调
function init(websocket){
$("#file").change(function(){
console.log($(this)[0].innerHtml)
// var objectURL=URL.createObjectURL($(this)[0].files[0]);
// console.log(objectURL);
// var reader = new FileReader();
// reader.onloadend=function() {
// if(reader.result.byteLength>0){
// //reader.result是一个含有视频数据流的Blob对象
// var buf = new Uint8Array(reader.result);
//
// //如果发送字节消息,第三个参数设置true
// websocket.send("/topic/server/byte",buf,true);
// console.log(">>> 已发送");
// }
// };
// reader.readAsArrayBuffer($(this)[0].files[0]);
var value = $("#file").val()
websocket.send("/topic/server/byte",value); //controller ->@MessageMapping("/server/byte")地址
console.log(">>> 已发送");
});
//订阅一个topic
websocket.subscribe("/topic/node",function(msg){
console.log(msg);
//字节消息
if(msg.isByte){
// var blob = new Blob([msg.body], { type: "image/jpg" });
// var objectURL = URL.createObjectURL(blob);
// $("#img").prop("src",objectURL);
// setTimeout(function(){
// URL.revokeObjectURL(objectURL);
// msg.body=null;
// },1000);
}
});
}
</script>
</html>
|