1、配置websocket
import org.springframework.context.annotation.Configuration;import org.springframework.messaging.simp.config.MessageBrokerRegistry;import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;import org.springframework.web.socket.config.annotation.StompEndpointRegistry;import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;@Configuration//通过该注解开启使用STMP协议来传输基于代理(message broker)的消息,//这时控制器支持使用@MessageMapping,就像使用@RequestMapping一样@EnableWebSocketMessageBrokerpublic class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) {//注册STOMP协议的节点(endpoint),并映射的指定的URL registry.addEndpoint("/endpointWisely").withSockJS();//注册一个STOMP的endpoint,并指定使用Sockjs协议 } @Override public void configureMessageBroker(MessageBrokerRegistry registry) {//配置消息代理(Message Broker) registry.enableSimpleBroker("/topic");//广播式应配置一个/topic消息代理 }}复制代码
2、消息类的定义
package com.yijialuo.websocket.domain;//浏览器向服务器发送的消息用此类接受public class WiselyMessage { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; }}复制代码
//服务端向浏览器发送此类消息public class WiselyResponse { private String responseMessage; public WiselyResponse(String responseMessage){ this.responseMessage=responseMessage; } public String getResponseMessage() { return responseMessage; } public void setResponseMessage(String responseMessage) { this.responseMessage = responseMessage; }}复制代码
3、控制器
import com.yijialuo.websocket.domain.WiselyMessage;import com.yijialuo.websocket.domain.WiselyResponse;import org.springframework.messaging.handler.annotation.MessageMapping;import org.springframework.messaging.handler.annotation.SendTo;import org.springframework.stereotype.Controller;@Controllerpublic class Wscontroller { @MessageMapping("/welcome")//当浏览器向服务端发送请求时,通过@MessageMapping映射/welcome这个地址,类似于@RequestMapping @SendTo("/topic/getResponse")//当服务端有消息时,会对订阅了@SendTo中的路径的浏览器发送消息 public WiselyResponse say(WiselyMessage message) throws Exception{ Thread.sleep(3000); return new WiselyResponse("Welcome,"+message.getName()+"!"); }}复制代码
4、配置viewController,为前端提供便捷的路径映射
public class WebMvcConfig extends WebMvcConfigurerAdapter{ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/ws").setViewName("/ws"); }}复制代码
前端:
引入sockjs.min.js和stomp.min.js
连接代码:
var socket = new SocketJS('/endpointWisely');
//和后台的registry.addEndpoint("/endpointWisely").withSockJS();对应
stompClient =Stomp.over(socket)//使用STOMP子协议的WebSocket客户端
stompClient.connect({}, function(fram) ) {//连接WebSocket服务器
stompClient.subscribe('/topic/getResponse' , function(respnose) {
//订阅/topic/getResponse(控制器的@SendTo),接收到消息触发function,数据在 //respnose.body
}
)
}
发送数据代码:
stompClient send("/welcome",{},JSON.stringify({'name':name}));
//welcome和后台Controller对应