1、引入jar,spring-websocket-starter
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、配置websocket config
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(myHandler(), "/myEndpoint").setAllowedOrigins("*");}public WebSocketHandler myHandler() {return new MyWebSocketHandler();}
}
3、使用实现websocket handler
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;public class MyWebSocketHandler extends TextWebSocketHandler {@Overridepublic void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {System.out.println("Received: " + message.getPayload());session.sendMessage(new TextMessage("Hello from server"));}
}
4、前端使用
<script>var socket = new WebSocket("ws://localhost:8080/myEndpoint");socket.onmessage = function(event) {console.log('Received from server:', event.data);};socket.onopen = function() {socket.send('Hello Server');};
</script>