【发布时间】:2019-04-12 22:21:35
【问题描述】:
我需要使用 SimpMessagingTemplate(或任何 JSON 格式的消息)从对象向我的客户端发送 stomp 消息
但是我的对象不是控制器,如果我将我的类声明为控制器,我的 Spring boot 应用程序由于未设置 bean 而无法启动。
我正在为我的学士论文创建一个托管在 Spring 服务器上的游戏。在我的应用程序中,我有房间,每个房间都有一个运行一个线程的游戏会话。
我目前有一个名为 RoomsController 的类,它像这样向服务器发送预定消息
@Controller
public class RoomsController {
@Autowired
private SimpMessagingTemplate template;
@Scheduled(fixedRate = 500)
public void updateRoomsInterface() throws Exception {
Game.getInstance().getRooms().forEach((k,v) -> {
if (v != null) {
System.out.println("Ted posilam do room " + k + " ktery se jmenuje " + v.getName() + " cely seznam hracu, schvalne co mi prijde, ok?");
Map <String, Player> playersList = v.getPlayers();
// String message = v.getPlayers().get;
this.template.convertAndSend("/topic/game/room/"+v.getID(), playersList);
}
});
}
}
这有点好,但我需要我的 GameSession 对象独立于服务器计时器(因为不同的游戏在不同的时间开始,我需要使用游戏的滴答声)
我的 GameSession 目前看起来像这样:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
public class GameSession extends Thread {
@Autowired
private SimpMessagingTemplate template;
private volatile boolean exit = false;
private Room room;
public GameSession(Room room) {
this.room = room;
status = "WAITING";
}
@Override
public void run() {
// dokud ne exit
while (!false) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendMessage();
}
}
public void sendMessage() {
System.out.println("Does this execute?");
this.template.convertAndSend("/topic/game/room/"+room.getID()+"/session", "THIS IS A TEST");
}
}
但是当它执行时,我在线程中得到一个异常
Does this execute?
Exception in thread "Thread-6" java.lang.NullPointerException
at cz.vse.pavm07.bp.objects.GameSession.sendMessage(GameSession.java:65)
at cz.vse.pavm07.bp.objects.GameSession.run(GameSession.java:34)
由于滴答声,我需要每个 gameSession 直接从 gameSession 对象发送消息。
我做错了什么?
【问题讨论】:
标签: java spring multithreading websocket sockjs