Here's my server app:
public static void Main()
{
try
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
Console.WriteLine("Starting TCP listener...");
TcpListener listener = new TcpListener(ipAddress, 500);
listener.Start();
while (true)
{
Console.WriteLine("Server is listening on " + listener.LocalEndpoint);
Console.WriteLine("Waiting for a connection...");
Socket client = listener.AcceptSocket();
Console.WriteLine("Connection accepted.");
Console.WriteLine("Reading data...");
byte[] data = new byte[100];
int size = client.Receive(data);
Console.WriteLine("Recieved data: ");
for (int i = 0; i < size; i++)
Console.Write(Convert.ToChar(data[i]));
Console.WriteLine();
client.Close();
}
listener.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.StackTrace);
Console.ReadLine();
}
}
From what it looks like, it's already always listening while running, but I'm still asking that to specify that I'd like both always-listening and multiple connection support.
How can I modify this to constantly listen while also accepting multiple connections?
The socket on which you listen for incoming connections is commonly referred to as the listening socket. When the listening socket acknowledges an incoming connection, a socket commonly referred to as a child socket is created that effectively represents the remote endpoint.
In order to handle multiple client connections simultaneously, you will need to spawn a new thread for each child socket on which the server will receive and handle data. Doing so will allow for the listening socket to accept and handle multiple connections as the thread on which you are listening will no longer be blocking or waiting while you wait for incoming data.
I had a similar problem today, and solved it like this:
My loop did not get stuck on waiting for a connection and it did accept multiple connections.