一,前端页面
1.原生请求
//建立连接 this.websocket = new WebSocket('ws://localhost:8085/websocket/user?token='+auth); //接收 this.websocket.onmessage = function(e){ console.log(e.data); } //发送 this.websocket.send(text);
2.sockJS请求
//建立连接 var sock = new SockJS('http://localhost:8085/websocket',null,{timeout: 30000}); var stomp = Stomp.over(sock); var headers = { login: 'mylogin', passcode: 'mypasscode', 'client-id': 'my-client-id', 'Authorization':auth}; stomp.connect(headers, function(frame){
//订阅主题 stomp.subscribe('/user/updateInfo',(resp)=>{ console.log(resp.body); resp.ack(); });
//发送 stomp.send("/user", {'Authorization': auth},payload);
二,gateway配置
spring: cloud: gateway: routes: # SockJS首次info路由 - id: websocket_sockjs_route uri: lb://testService predicates: - Path=/websocket/info/** # Websocket原生路由 - id: websocket_route uri: lb:ws://testService predicates: - Path=/websocket/**
三,服务端
1.tomcat实现
@Configuration public class WebsocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter( ) { return new ServerEndpointExporter(); } } @Component @ServerEndpoint("/websocket/user") public class WebsocketController { Session testSession = null; @OnOpen public void onOpen(Session session){ testSession = session; System.out.println("ws connected!!"); sendMessage("ws connected!!"); } @OnMessage public void onMessage(String msg,Session session){ System.out.println("msg '" +msg+ "' received!!"); try { sendMessage("msg '" +msg+ "' received!"); } catch (InterruptedException e) { e.printStackTrace(); } } public void sendMessage(String msg) { try { this.testSession.getBasicRemote().sendText(msg); } catch (IOException e) { e.printStackTrace(); } } @OnClose public void onClose(Session session){ System.out.println("ws closed!!"); } }
2.spring实现
@Configuration @EnableWebSocket public class WebsocketSpringConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new WebsocketSpringController(),"/websocket/user").addInterceptors(new WebsocketInterceptor()).setAllowedOrigins("http://localhost"); } } public class WebsocketInterceptor implements HandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception { map.put("token",""); return true; } @Override public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) { } } public class WebsocketSpringController extends TextWebSocketHandler { private final String charset = "UTF-8"; private WebSocketSession session; @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { this.session = session; System.out.println(session); session.sendMessage(new TextMessage("connected...")); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); System.out.println(payload); session.sendMessage(new TextMessage("received:" + payload)); } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { super.handleTransportError(session, exception); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { super.afterConnectionClosed(session, status); } }