Mann Maurya

Mann Maurya

  • NA
  • 104
  • 9.6k

How to close the continues reading of port when server OFF

Jun 5 2019 1:25 AM
public void TcpListener()
{
// set the TcpListener on port 1080
int port = 1080;
TcpListener server = new TcpListener(IPAddress.Any, port);
try
{
while (true)
{
Console.Write("Waiting for a connection... ");
// Start listening for client requests
server.Start();
client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
NetworkStream stream = client.GetStream();
int i;
i = stream.Read(bytes, 0, bytes.Length);
while(i != 0)
{
data = System.Text.Encoding.Default.GetString(bytes, 0, i);
Console.WriteLine(String.Format("Received: {0}", data));
 
hexString = "0800630003000000006301";
HexString2Ascii(hexString);
 
msgSend = System.Text.Encoding.ASCII.GetBytes(Send);
stream.Write(msgSend, 0, msgSend.Length);
 
Console.WriteLine(String.Format("Sent: {0}", data));
 
i = stream.Read(bytes, 0, bytes.Length);
}
}
client.Close();
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
}
 
I want that port should always be in listening mode (achieved).
but when server pc shutdown or software closed, because of port is continue in listening mode it throws an error.
 
Line : i = stream.Read(bytes, 0, bytes.Length);
 
Error : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. 
 
basically I just want how to stop port from listening when software closed or Sever PC Shutdown , also in a listening mode when the Server pc working fine. 
 
 

Answers (2)