我基于 Spring 框架实现了自己的 Websocket 应用程序并使用了相同的配置:http : //docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html
服务器端代码:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
}
Run Code Online (Sandbox Code Playgroud)
客户端代码:*.jsp 文件
/*
*connect to websocket
*/
function connect() {
var socket = new SockJS("<c:url value='/ws'/>");
stompClient = Stomp.over(socket);
stompClient.connect();
}
function disconnect() {
stompClient.disconnect();
setConnected(false);
console.log("Disconnected");
}
Run Code Online (Sandbox Code Playgroud)
pom.xml 依赖项:
<!-- Spring websocket and messaging …Run Code Online (Sandbox Code Playgroud)