Untitled

mail@pastecode.io avatar
unknown
plain_text
15 days ago
2.4 kB
0
Indexable
Never
using Microsoft.AspNetCore.Mvc;
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SocketApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SocketController : ControllerBase
    {
        private const string serverIpAddress = "127.0.0.1"; // Indirizzo IP del server socket
        private const int serverPort = 8080; // Porta del server socket
        private TcpClient _tcpClient;
        private NetworkStream _stream;

        public SocketController()
        {
            _tcpClient = new TcpClient();
            _tcpClient.Connect(serverIpAddress, serverPort);
            _stream = _tcpClient.GetStream();
        }

        [HttpPost("initialize")]
        public async Task<IActionResult> InitializeSystem()
        {
            try
            {
                await SendMessageAsync("INITIALIZE");
                return Ok("Sistema inizializzato con successo.");
            }
            catch (Exception ex)
            {
                return StatusCode(500, "Errore durante l'inizializzazione del sistema: " + ex.Message);
            }
        }

        [HttpPost("call")]
        public async Task<IActionResult> CallServer([FromBody] string command)
        {
            try
            {
                await SendMessageAsync(command);
                return Ok("Comando inviato con successo al server.");
            }
            catch (Exception ex)
            {
                return StatusCode(500, "Errore durante l'invio del comando al server: " + ex.Message);
            }
        }

        [HttpPost("shutdown")]
        public async Task<IActionResult> ShutdownSystem()
        {
            try
            {
                await SendMessageAsync("SHUTDOWN");
                return Ok("Sistema spento con successo.");
            }
            catch (Exception ex)
            {
                return StatusCode(500, "Errore durante lo spegnimento del sistema: " + ex.Message);
            }
        }

        private async Task SendMessageAsync(string message)
        {
            byte[] data = Encoding.ASCII.GetBytes(message);
            await _stream.WriteAsync(data, 0, data.Length);
        }

        // Chiudi la connessione quando il servizio viene distrutto
        ~SocketController()
        {
            _stream.Close();
            _tcpClient.Close();
        }
    }
}
Leave a Comment