问题:在@ServerEndpoint类@Autowired豆空的WebSockets JSR 356 Spring集成@ServerEndpoint
我怎样才能确保此WebSocketController类下面将豆子被注入,这是我怎样才能使它由Spring管理?我可以连接到websocket所以它的工作原理,但在WebSocketController类实例中gameService始终为null,所以我认为它是由tomcat以某种方式创建的,而不是Spring。
我正在使用Spring引导。我只需要弄清楚如何将bean注入到这个websocket控制器类中。
WebSocketController类
@Component
@ServerEndpoint("/sock")
public class WebSocketController {
@Autowired
private GameService gameService;
private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>());
@OnMessage
public void handleMessage(Session session, String message) throws IOException {
session.getBasicRemote().sendText(
"Reversed: " + new StringBuilder(message).reverse());
}
@OnOpen
public void onOpen(Session session) {
clients.add(session);
System.out.println("New client @"+session.getId());
if (gameService == null) System.out.println("game service null");
}
@OnClose
public void onClose(Session session) {
clients.remove(session);
System.out.println("Client disconnected @" + session.getId());
}
}
GameService接口和实现
public interface GameService {
List<Character> getCharacters();
}
@Service
public class GameServiceMockImpl implements GameService {
@Override
public List<Character> getCharacters() {
List<Character> list = new ArrayList<>();
list.add(new Character("aaa","1.png",100));
list.add(new Character("aaa","2.jpg",100));
list.add(new Character("aaa","3.jpg",100));
return list;
}
}
应用类
@SpringBootApplication
public class App {
public static void main(String args[]){
SpringApplication.run(App.class,args);
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
编辑:
使用Spring 4瓦ebSockets根本无法工作,我甚至无法通过浏览器进行连接。
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/myHandler");
}
@Bean
public WebSocketHandler myHandler() {
return new MyHandler();
}
}
public class MyHandler extends TextWebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
System.out.println(message.getPayload());
}
}
谢谢回答。我宁愿使用Spring 4 WebSocket,我也想使用没有SockJS的“直接方法”。所以我创建了TextWebSocketHandler和WebSocketConfigurer。但它不起作用。我无法从浏览器连接。它在控制台中表示它将给定的URL映射到文本处理程序,但仍然无法连接。我在主帖中添加了代码。 – Greyshack
我不得不允许来自其他来源的连接,它的工作原理。所以最后我使用Spring 4 websockets。 – Greyshack
这很酷,但我不认为它是最佳做法。 – Pulkit