web.xml导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
springboot可以使用一个端口即提供http服务,也可以作为websocket服务,取决于用什么协议来访问它
websocket配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
/**
* 注册handle
* @see org.springframework.web.socket.config.annotation.WebSocketConfigurer#registerWebSocketHandlers(org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry)
*/
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(),"/").addInterceptors(new HttpSessionHandshakeInterceptor()).setAllowedOrigins("*");
}
@Bean
public WebSocketHandler myHandler(){
return new MyMessageHandler();
}
}
如果跨域的话注意加上setAllowedOrigins("*");
在消息处理类中,建立连接后把session信息存在ConCurrentHashMap中
public class MyMessageHandler implements WebSocketHandler {
public final static Map<String, WebSocketSession> userMap = new ConcurrentHashMap<String, WebSocketSession>();
......
@Override
public void afterConnectionEstablished(WebSocketSession session)
throws Exception {
String userId = this.getUserId(session);
if (StringUtils.isNoneBlank(userId)) {
userMap.put(userId, session);
session.sendMessage(new TextMessage("建立服务端连接成功!"));
}
}
}
写一个http路由方法,通过调用map中session的sendMessage方法即可发送消息,如果需要获取异步返回值的话可以把返回值放到Redis里,再加一个方法通过获取redis里的状态值
@ResponseBody
@RequestMapping(value = "/sendcommand/{devId}",method = RequestMethod.POST)
public Object sendcommand(@PathVariable(required = false) String devId,
@RequestHeader(value="token", required = false) String token,
@RequestBody String body, HttpServletResponse response
) {
WebSocketSession session = MyMessageHandler.getSession(devId);
if (session != null && session.isOpen()) {
try {
TextMessage message = new TextMessage(body);
session.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
return new JsonError(e.getMessage());
}
return new JsonSuccess();
}
return new JsonError("offline");
}