tcp服务
This commit is contained in:
@@ -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; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user