I have developed this small multi-threaded socket server, that creates one socket to not block the main program, and another thread for each new accepted connection.
The question comes when reading the data, I have a method called receiveData that reads all the data input, so right now the code only reads one time for each connection.
I solved this by adding inside the method receiveData a while loop with the flag socket.CanRead, what does this flag exactly do? What difference is there between CanRead and DataAvailable?
class Server
{
static void receiveData(TcpClient client, NetworkStream stream)
{
byte[] bytes = new byte[client.ReceiveBufferSize];
stream.Read (bytes, 0, (int) client.ReceiveBufferSize);
string returndata = Encoding.UTF8.GetString (bytes);
Console.WriteLine ("SERVER RECEIVED: " + returndata);
}
static void startServer()
{
new Thread(() =>
{
TcpListener listener = new TcpListener(IPAddress.Any, 5000);
listener.Start();
while (true)
{
if (listener.Pending()) {
new Thread(() =>
{
TcpClient client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
Server.receiveData(client, stream);
}).Start();
}
}
}).Start();
}
static void Main(string[] args)
{
Server.startServer ();
}
}