我正在嘗試在Spring 4中使用websocket Java。我創建了一個服務器處理程序。 這裏是我的代碼Websocket Spring 4
import java.util.logging.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
public class ServerHandler extends TextWebSocketHandler{
\t
\t private Logger logger = Logger.getLogger(this.getClass().getName());
\t
\t @Override
\t public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
\t \t // TODO Auto-generated method stub
\t \t logger.info("Connection clodes with websocket server: session id " + session.getId());
\t }
\t
\t @Override
\t public void afterConnectionEstablished(WebSocketSession session) throws Exception {
\t \t // TODO Auto-generated method stub
\t \t logger.info("Connected user with websocket server: session id " + session.getId());
\t }
\t
\t @Override
\t public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
\t \t // TODO Auto-generated method stub
\t \t
\t \t super.handleMessage(session, message);
\t }
\t
\t @Override
\t public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
\t \t // TODO Auto-generated method stub
\t \t super.handleTransportError(session, exception);
\t }
}
接下來,我創建了一個WebSocket的配置者。下面是代碼
import org.springframework.context.annotation.Bean;
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{
\t
\t @Override
\t public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
\t \t registry.addHandler(myHandler(), "/websocket").withSockJS();
\t \t
\t }
\t
\t @Bean
public ServerHandler myHandler() {
return new ServerHandler();
}
\t
}
在我的客戶(JavaScript的),我試圖連接到服務器
var sock = new SockJS('http://localhost:9999/websocket');
,當我試圖執行客戶端,我有404錯誤 問題在哪裏?
你有沒有找到解決這個問題的辦法? –