How to set TCPListener to always listen and when new connection discard current code example
Example: How to set TCPListener to always listen and when new connection discard current
private static void Listener()
{
TcpListener server = null;
try
{
// Set the TcpListener on carPort.
var port = 5001;
var ipAddress = IPAddress.Parse("192.168.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(ipAddress, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
var bytes = new byte[256];
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... \n");
// Perform a blocking call to accept requests.
var client = server.AcceptTcpClient();
if (client.Connected)
{
Console.WriteLine("Connected!");
// Get a stream object for reading
NetworkStream stream = client.GetStream();
while (true)
{
if (stream.DataAvailable)
{
// Loop to receive all the data sent by the client.
var i = stream.Read(bytes, 0, bytes.Length);
var data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
var ba = Encoding.ASCII.GetBytes("\nData Received\n");
stream.Write(ba, 0, ba.Length);
}
else
{
if (!server.Pending()) continue;
Console.WriteLine("found new client");
break;
}
}
Console.WriteLine("Client close");
// Shutdown and end connection
client.Close();
}
Thread.Sleep(100);
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
Console.WriteLine("Stop listening for new clients.");
server?.Stop();
}
}
// see original on the page -> https://stackoverflow.com/questions/35322605/how-to-set-tcplistener-to-always-listen-and-when-new-connection-discard-current