|
|
@@ -0,0 +1,52 @@
|
|
|
+package com.izouma.meta.web;
|
|
|
+
|
|
|
+import com.izouma.meta.websocket.MMOWebSocket;
|
|
|
+import lombok.AllArgsConstructor;
|
|
|
+import org.springframework.web.bind.annotation.GetMapping;
|
|
|
+import org.springframework.web.bind.annotation.PathVariable;
|
|
|
+import org.springframework.web.bind.annotation.RequestMapping;
|
|
|
+import org.springframework.web.bind.annotation.RestController;
|
|
|
+
|
|
|
+import java.util.Map;
|
|
|
+import java.util.concurrent.*;
|
|
|
+
|
|
|
+@RestController
|
|
|
+@RequestMapping("/mmo/websocket")
|
|
|
+@AllArgsConstructor
|
|
|
+public class MMOWebSocketController {
|
|
|
+
|
|
|
+ private static final String NICK_NAME = "metaRobot";
|
|
|
+ private static final String USER_ID = "7970191";
|
|
|
+ private static final String MESSAGE_BODY = "{type:9,objectId:%S}";
|
|
|
+ private static final long DELAY_MS = 0;
|
|
|
+ private static final long PERIOD_MS = 200;
|
|
|
+
|
|
|
+ private MMOWebSocket mmoWebSocket;
|
|
|
+
|
|
|
+ private final Map<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();
|
|
|
+
|
|
|
+ @GetMapping("/{objectId}/start")
|
|
|
+ public synchronized void startSendingMessages(@PathVariable String objectId) {
|
|
|
+ if (tasks.containsKey(objectId)) {
|
|
|
+ throw new IllegalArgumentException(String.format("Task with id %S is already running", objectId));
|
|
|
+ }
|
|
|
+ ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
|
|
|
+ ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> sendMessage(objectId), DELAY_MS, PERIOD_MS, TimeUnit.MILLISECONDS);
|
|
|
+ tasks.put(objectId, future);
|
|
|
+ }
|
|
|
+
|
|
|
+ @GetMapping("/{objectId}/stop")
|
|
|
+ public synchronized void stopSendingMessages(@PathVariable String objectId) {
|
|
|
+ ScheduledFuture<?> future = tasks.get(objectId);
|
|
|
+ if (future != null) {
|
|
|
+ future.cancel(false);
|
|
|
+ tasks.remove(objectId);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void sendMessage(String objectId) {
|
|
|
+ if (mmoWebSocket != null) {
|
|
|
+ mmoWebSocket.onMessage(NICK_NAME, USER_ID, String.format(MESSAGE_BODY, objectId), null);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|