Desenvolvi uma aplicação Windows Form C# que deve ficar conectado sempre, não deve ter interrupções.
O sistema recebe via Tcp/Ip informações de um receptor Rfid que quando solicitado passará uma sequencia de caracteres para o cliente Windows Form que desenvolvi.
Este receptor Rfid esta configurado com KeepAlive de 60 segundos, mas mesmo assim no decorrer do dia o meu sistema Windows Form perde a conexão com o receptor.
Como faço para que de tempo em tempo, faço meu sistema Windows Form dar um Close() na conexão e logo após Conectar novamente assim penso Eu que manterei o sistema sempre em funcionamento, não sei se é uma boa pratica, mas este sistema deve sempre estar conectado.
public partial class Form1 : Form
{
readonly TcpClient clientSocket = new TcpClient();
NetworkStream serverStream = default;
string readData = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox4.Text = string.Empty;
try
{
clientSocket.Connect(textBox1.Text, int.Parse(textBox2.Text));
Thread ctThead = new Thread(GetMessage);
ctThead.Start();
textBox1.Enabled = false;
textBox2.Enabled = false;
label4.Text = "Sistema conectado";
}
catch (Exception)
{
while (!clientSocket.Connected)
{
Thread.Sleep(5000);
Form1_Load(sender, e);
}
}
}
private void GetMessage()
{
while (true)// <----------- Aqui perde a conexão
{
serverStream = clientSocket.GetStream();
var buffSize = clientSocket.ReceiveBufferSize;
byte[] insTream = new byte[buffSize];
serverStream.Read(insTream, 0, buffSize);
string returnData = Encoding.ASCII.GetString(insTream);
readData = returnData;
Msg();
}
}
private void Msg()
{
this.textBox4.Invoke((MethodInvoker)async delegate ()
{
try
{
textBox4.Text = readData.Substring(0, readData.IndexOf("\r"));
if (readData.Contains("0x300"))
{
string MensagemFormatoJson = "{'Tag': '" + textBox4.Text + "'}";
try
{
using (var client = new HttpClient())
{
var response = await client.PostAsync(
"https://meusitereceptor/api/OrdensChegadas",
new StringContent(MensagemFormatoJson, Encoding.UTF8, "application/json")
);
}
textBox4.Text = readData;
}
catch (Exception /*exception*/)
{
//textBox4.Text += " Exception " + exception.Message.ToString();
}
}
}
catch (Exception exception)
{
textBox4.Text += "Exception " + exception.Message.ToString();
}
});
}
}//
}//