wanshenmean
2026-03-19 c493779a8504fe1eb548c865ff268a7f7436ec01
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using Microsoft.AspNetCore.Mvc;
using WIDESEAWCS_S7Simulator.Core.Entities;
using WIDESEAWCS_S7Simulator.Core.Interfaces;
 
namespace WIDESEAWCS_S7Simulator.Server.Controllers
{
    /// <summary>
    /// 客户端连接管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class ClientsController : ControllerBase
    {
        private readonly ISimulatorInstanceManager _instanceManager;
        private readonly ILogger<ClientsController> _logger;
 
        public ClientsController(
            ISimulatorInstanceManager instanceManager,
            ILogger<ClientsController> logger)
        {
            _instanceManager = instanceManager ?? throw new ArgumentNullException(nameof(instanceManager));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }
 
        /// <summary>
        /// 获取连接的客户端列表
        /// </summary>
        [HttpGet("GetConnectedClients")]
        [ProducesResponseType(typeof(List<S7ClientConnection>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public ActionResult<List<S7ClientConnection>> GetConnectedClients(string id)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return BadRequest(new { error = "Instance ID is required" });
                }
 
                var instance = _instanceManager.GetInstance(id);
                if (instance == null)
                {
                    return NotFound(new { error = $"Instance with ID '{id}' not found" });
                }
 
                var state = instance.GetState();
                return Ok(state.Clients);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to get clients for instance {InstanceId}", id);
                return StatusCode(StatusCodes.Status500InternalServerError, new { error = "Failed to retrieve clients" });
            }
        }
 
        /// <summary>
        /// 断开指定客户端
        /// </summary>
        [HttpDelete("DisconnectClient")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public ActionResult DisconnectClient(string id, string clientId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return BadRequest(new { error = "Instance ID is required" });
                }
 
                if (string.IsNullOrWhiteSpace(clientId))
                {
                    return BadRequest(new { error = "Client ID is required" });
                }
 
                var instance = _instanceManager.GetInstance(id);
                if (instance == null)
                {
                    return NotFound(new { error = $"Instance with ID '{id}' not found" });
                }
 
                var state = instance.GetState();
                var client = state.Clients.FirstOrDefault(c => c.ClientId == clientId);
 
                if (client == null)
                {
                    return NotFound(new { error = $"Client with ID '{clientId}' not found" });
                }
 
                // Note: The actual disconnection logic would need to be implemented in IS7ServerInstance
                // For now, we're returning a success response indicating the operation was requested
                // In a real implementation, you would call instance.DisconnectClient(clientId)
                _logger.LogInformation("Disconnect request for client {ClientId} on instance {InstanceId}", clientId, id);
 
                return Ok(new
                {
                    message = "Client disconnect requested",
                    clientId = clientId,
                    instanceId = id,
                    note = "Actual disconnection logic should be implemented in IS7ServerInstance"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to disconnect client {ClientId} for instance {InstanceId}", clientId, id);
                return StatusCode(StatusCodes.Status500InternalServerError, new { error = "Failed to disconnect client" });
            }
        }
    }
}