第一步
引入Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
第二步
配置WebSocketConfig
registry.addHandler()内为自定义消息接收发送Handler和自定义名称
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer, WebMvcConfigurer {
@Resource
private SystemWebSocketHandler systemWebSocketHandler;
@Resource
private AcceptBusinessWebSocketHandler acceptBusinessWebSocketHandler;
@Resource
private EmbeddedServerWebSocketHandler embeddedServerWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(systemWebSocketHandler, "/webSocketServer").addHandler(acceptBusinessWebSocketHandler,"/acceptBusinessInfo").addHandler(embeddedServerWebSocketHandler,"/embeddedServer").addInterceptors(new HandShakeInterceptor()).setAllowedOrigins("*");
}
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
//接收消息大小设置为5M
container.setMaxTextMessageBufferSize(5 * 1024 * 1024);
container.setMaxBinaryMessageBufferSize(5 * 1024 * 1024);
return container;
}
}
第三步
自定义一个类实现WebSocketHandler
package com.visionvera.remoteservice.ws;
import com.alibaba.fastjson.JSON;
import com.visionvera.api.handler.bean.EmbeddedEntity;
import com.visionvera.api.handler.bean.EmbeddedInfo;
import com.visionvera.common.utils.RedisUtils;
import com.visionvera.remoteservice.bean.EmbeddedServerInfo;
import com.visionvera.remoteservice.dao.EmbeddedServerDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Created by jlm on 2019-05-15 15:24 服务连接
*/
@Component
public class EmbeddedServerWebSocketHandler implements WebSocketHandler {
private static Logger logger = LoggerFactory.getLogger(EmbeddedServerWebSocketHandler.class);
private static final CopyOnWriteArrayList<WebSocketSession> sessionList = new CopyOnWriteArrayList<>();
@Resource
private EmbeddedServerDao embeddedServerDao;
@Resource
private RedisUtils redisUtils;
private String data = "";
//建立连接
@Override
public void afterConnectionEstablished(WebSocketSession session) {
logger.info("建立连接");
sessionList.add(session);
String url = session.getUri().toString();
int index = url.lastIndexOf("=");
String vcDevId = url.substring(index + 1);
embeddedServerDao.insertEmbeddedServer(vcDevId,session.getId());
}
//失去连接
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
logger.info("失去连接");
sessionList.remove(session);
embeddedServerDao.deleteEmbeddedServer(session.getId());
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws IOException {
logger.error("Exception occurs on webSocket connection. disconnecting....");
if (session.isOpen()) {
session.close();
}
sessionList.remove(session);
embeddedServerDao.deleteEmbeddedServer(session.getId());
}
//收到消息进行处理
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
//这里对接收到的消息进行处理,注意消息过长时,websocket会分多次进行接收,注意拼接
}
@Override
public boolean supportsPartialMessages() {
return true;
}
/**
* 定向发送消息
* @param message
* @param vcDevId
*/
public void sendMessageToEmbeddServer(WebSocketMessage<?> message,String vcDevId){
for (WebSocketSession session : sessionList) {
//遍历所有连接,根据自定义的字段去匹配连接,找到对应session就可以实现定向发送
}
}
}
}
注意:
1.项目有Shiro权限控制,要放开websocket,否则访问不到
2. 通过nginx代理访问前端页面实现websocket通信,要修改nginx配置文件
server
{
#client_max_body_size 100m;
listen 6061;
server_name localhost;
location / {
root 前端包路径;
index index.html index.htm;
}
location /remoteservice {
proxy_pass http://后端ip地址端口号;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
}
}