tcp服务

This commit is contained in:
2026-03-11 17:44:06 +08:00
parent fb05360c5e
commit 2cb03b146a
11 changed files with 494 additions and 0 deletions

View File

@@ -0,0 +1,77 @@
package top.wms.admin.controller.tcp;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.wms.admin.tcp.config.SimpleRequestMatcher;
import top.wms.admin.tcp.manager.ChannelManager;
@Slf4j
@RestController
@RequestMapping("/vm")
public class VmCommandController {
@Autowired
private ChannelManager channelManager;
@Autowired
private SimpleRequestMatcher requestMatcher;
@GetMapping("/send")
public String sendAndWait(@RequestParam String msg) {
// 1. 检查连接
Channel channel = channelManager.getFirstChannel();
if (channel == null) {
return "ERROR: VM未连接";
}
// 2. 直接发送消息不加requestId
String sendMsg = msg;
channel.writeAndFlush(sendMsg);
log.info("发送指令: {}", sendMsg);
// 3. 等待响应不传requestId
String response = requestMatcher.waitForResponse(20);
// 4. 返回结果
if ("TIMEOUT".equals(response)) {
return "ERROR: 处理超时";
}
return response; // 直接返回VM的响应
}
@PostMapping("/command")
public String sendCommand(@RequestBody CommandRequest request) {
Channel channel = channelManager.getFirstChannel();
if (channel == null) {
return "ERROR: VM未连接";
}
// 直接发送请求的命令
String sendMsg = request.getCommand();
channel.writeAndFlush(sendMsg + "\n");
log.info("发送指令: {}", sendMsg);
// 等待响应
String response = requestMatcher.waitForResponse(request.getTimeout());
if ("TIMEOUT".equals(response)) {
return "ERROR: 处理超时";
}
return response;
}
/**
* 请求体类
*/
public static class CommandRequest {
private String command;
private int timeout = 5; // 默认5秒
public String getCommand() { return command; }
public void setCommand(String command) { this.command = command; }
public int getTimeout() { return timeout; }
public void setTimeout(int timeout) { this.timeout = timeout; }
}
}