Zdravím.
Chtěl bych se zeptat, jak kontrolovat zda je zařízení připojeno v síti, pokud ano, jak se s ním spojit. Jinak zavřit spojení a třeba čekat na spojení.
Např. Vyvíjím aplikaci na ARMu, kde mám funkční LAN-ku. Ale vždy, když uploadnu firmware, tak se mi spojení rozpadne a musím opět kliknout na tlačítko connect, čímž povolím tlačítko connect a hned musím kliknout na tlačítko connect a se zařízením se spojím.
Dá se toto nějak automatizovat? Mám IP, mám PORT. Nějak ani nevím, jak na to.
Program je zde. Není nijak komplikovaný, vycházel jsem z examplu na internetu. Tak třeba někdo poradí, co musím udělat. Díky moc
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using int8_t = System.SByte;
using uint8_t = System.Byte;
using int16_t = System.Int16;
using uint16_t = System.UInt16;
using uint32_t = System.UInt32;
namespace WiFly_communication_test
{
public partial class Form1 : Form
{
/*TPCclient promenna jako globalni, protoze jsou pouzivany ruzne */
private TcpClient myClient;
private NetworkStream stream;
public Form1()
{
InitializeComponent();
}
/* Odstrani Tlacika na liste */
private const int WS_SYSMENU = 0x80000;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style &= ~WS_SYSMENU;
return cp;
}
}
/* Funkce, ktera se provede hned po spusteni programu */
private void Form1_Load(object sender, EventArgs e)
{
btnConnect.Enabled = true;
btnStop.Enabled = false;
btnSend.Enabled = false;
ButtonDisable();
SchovejStatus();
indikator.Text = "Offline";
indikator.BackColor = Color.Red;
timer1.Start();
groupBox4.Hide();
groupBox2.Hide();
}
static int trest = 0;
public bool Connected { get; }
static double OfsetValue, uhelOtoceni;
static long cas = 0;
static Int16 VlaknoJede = 0;
static void Pis()
{
while (VlaknoJede == 1)
{
cas++;
Thread.Sleep(TimeSpan.FromSeconds(1)); // Přeruší práci vlákna na 1 vteřin
}
}
/* Povoli zobrazeni status zprav */
private void ZobrazStatus()
{
polohaX.Enabled = true;
polohaY.Enabled = true;
natoceni.Enabled = true;
ofset.Enabled = true;
}
/* Zakaze status zpravy */
private void SchovejStatus()
{
polohaX.Enabled = false;
polohaY.Enabled = false;
natoceni.Enabled = false;
ofset.Enabled = false;
}
/* funkce, ktera zakaze jednotlive tlacitka */
private void ButtonDisable()
{
}
/* funkce, ktera povoli jednotlive tlacitka k odesilani zprav */
private void ButtonEnable()
{
}
/* timto tlacitkem odesli data napsana v radku */
private void btnSend_Click(object sender, EventArgs e)
{
/*nactu data do pole a odesli jako strem*/
Byte[] data = System.Text.Encoding.ASCII.GetBytes(txtSend.Text + "\r\n");
stream.Write(data, 0, data.Length);
txtTalk.AppendText("Odeslana zprava: " + txtSend.Text);
if (checkBox1.Checked) txtSend.Clear(); //Smazu textbox, jakmile data odesli
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
/*Rozdeleni dat jako IP, PORT a pripojeni ke klientovi*/
txtTalk.Clear();
myClient = new TcpClient(textBox1.Text, int.Parse(textBox2.Text));
stream = myClient.GetStream();
txtTalk.AppendText("Pripojeno k: " + textBox1.Text + ":" + textBox2.Text + "\r\n");
backgroundWorker1.RunWorkerAsync();
btnSend.Enabled = true;
btnStop.Enabled = true;
btnConnect.Enabled = false;
ButtonEnable();
ZobrazStatus();
indikator.Text = "Online";
indikator.BackColor = Color.Green;
VlaknoJede = 1;
cas = 0;
Thread t = new Thread(Pis);
t.Start();
groupBox4.Show();
groupBox2.Show();
}
catch
{
MessageBox.Show("Chyba spojeni!\r\n");
}
}
private void ResetLabelText()
{
polohaX.ResetText();
polohaY.ResetText();
natoceni.ResetText();
ofset.ResetText();
}
private void btnStop_Click(object sender, EventArgs e)
{
try
{
/*odpojeni od serveru. */
txtTalk.AppendText("Odpojeno\r\n");
stream.Close();
myClient.Close();
btnStop.Enabled = false;
btnConnect.Enabled = true;
btnSend.Enabled = false;
ButtonDisable();
SchovejStatus();
indikator.Text = "Offline";
indikator.BackColor = Color.Red;
ResetLabelText();
VlaknoJede = 0;
groupBox4.Hide();
groupBox2.Hide();
}
catch
{
MessageBox.Show("Nelze odpojit!\r\n");
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
/*Naslouchat pro příchozí zprávy na dobu neurčitou, dokud je přerušeno spojení*/
while (myClient.Connected)
{
if (!stream.DataAvailable)
{
System.Threading.Thread.Sleep(25);
continue;
}
Byte[] data = new Byte[256];
String responseData = String.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
backgroundWorker1.ReportProgress(0, responseData);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
txtTalk.AppendText(e.UserState.ToString()); //Vypise prijata data
}
catch
{
MessageBox.Show("Že ty jsi řádně neukončil spojení!");
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//txtTalk.AppendText("Background worker stopped\r\n");
}
private void btnClear_Click(object sender, EventArgs e)
{
txtTalk.Clear();
label27.Text = trest.ToString();
}
/*Server variables have global scope for simplicity*/
private TcpListener tcpListener;
private Thread listenThread;
private void btnStart_Click(object sender, EventArgs e)
{
/*Start listener and kick to new thread to free the UI*/
tcpListener = new TcpListener(IPAddress.Any, int.Parse(textBox2.Text));
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
this.Invoke((MethodInvoker)delegate
{
//This unnamed delegate is used to access UI elements on the main thread
txtTalk.AppendText("Server start\r\nNasloucham Klientum...\r\n");
});
}
private void ListenForClients()
{
/*Listner thread for connections, runs indefinitely until server stopped
kicks incomming connection communication to new thread*/
tcpListener.Start();
try
{
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient(); //blocking call
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
this.Invoke((MethodInvoker)delegate
{
txtTalk.AppendText("Klient pripojen\r\n");
});
}
}
catch (SocketException)
{
//This exception is thrown when server is terminated
//caught just so that the program doesn't crash
}
finally
{
this.Invoke((MethodInvoker)delegate
{
txtTalk.AppendText("Server zastaven\r\n");
});
}
}
private void HandleClientComm(object client)
{
/*Handles all communication once server receives client*/
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
bytesRead = clientStream.Read(message, 0, message.Length); //blocking call
}
catch (Exception ex)
{
txtTalk.AppendText("ERROR: " + ex.Message + "\r\n");
break;
}
if (bytesRead == 0)
{
break;
}
ASCIIEncoding encoder = new ASCIIEncoding();
this.Invoke((MethodInvoker)delegate
{
txtTalk.AppendText("Prijato: " + encoder.GetString(message, 0, bytesRead) + "\r\n");
});
}
tcpClient.Close();
this.Invoke((MethodInvoker)delegate
{
txtTalk.AppendText("Klient odpojen\r\n");
});
}
private void btnStopServ_Click(object sender, EventArgs e)
{
/*Stops the server
Note that because stop() will cause the listener to terminate with an exception (see above)
any code after this statement in this event handler will be skipped*/
tcpListener.Stop();
/*DON'T PUT ANYTHING HERE, NEVER EXECUTES*/
}
private void button1_Click(object sender, EventArgs e)
{
try
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes(textBox3.Text + "\r\n");
stream.Write(data, 0, data.Length);
txtTalk.AppendText("Odeslana zprava: " + textBox3.Text + "\r\n");
}
catch
{
MessageBox.Show("Data nelze odeslat!\r\n");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
label27.Text = DateTime.Now.ToString("HH:mm:ss - dd.MM.yyyy");
}
private void button11_Click(object sender, EventArgs e)
{
Environment.Exit(0);
Application.Exit();
}
}
}