G
gaggs1
Guest
We have software (Winforms application) that communicates with hardware but sometimes we need to change the hardware but we need also to close old hadware connection and re connect the software with the new hardware on same port and address (deponds of user choice). I have tried to close Tcp connection by
client.Close();
listener.Stop();
before closing my form to switch to an other option(changing device).
when i lunch the new connection the instruction:
listener.Start();
My hall Code:
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
TcpListener server = null;
while (!m_StopThread)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(System.Net.IPAddress.Any, PORT_NO);
listener.Start();
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
if (dataReceived != "")
{
string dataReceived1 = dataReceived.Substring(0, 24);
Console.WriteLine("Received : " + dataReceived);
Console.WriteLine("dataLength : " + dataReceived.Length);
while (dataReceived.Length > 48)
{
xx.Add(dataReceived.Substring(0, 24));
dataReceived = dataReceived.Substring(28);
}
dataReceived = dataReceived.Substring(0, 24);
xx.Add(dataReceived);
int x = xx.Count;
Console.WriteLine("LenghtArray : " + x);
for (int i = 0; i < xx.Count; i++)
{
Console.WriteLine("Array ele : " + xx);
name1 = chargeN(xx);
prix1 = chargeP(xx);
m = m + "#" + name1 + "*" + prix1;
Inseert(xx);
}
//---write back the text to the client---
byte[] msg = System.Text.Encoding.ASCII.GetBytes(m);
Console.WriteLine("Sending back : " + m);
// Send back a response.
nwStream.Write(msg, 0, msg.Length);
}
client.Close();
listener.Stop();
}
}).Start();
}
I have 2 Forms in my code and those of two had this piece of code.
Continue reading...