I’m trying to connect TcpClient (client-side) and TcpListener (server-side) to send (more than one) data stream. I have a problem that I could not solve by reading docs and articles…
This is the method I use to start TcpListener (server-side):
public void StartListener()
{
System.Net.Sockets.TcpListener listener = new(
IPAddress.Parse("127.0.0.1"),
15001);
listener.Start();
while (listen)
{
if (listener.Pending())
{
try
{
Thread thread = new Thread(() =>
{
using (TcpClient tcpClient = listener.AcceptTcpClient())
using (NetworkStream networkStream = tcpClient.GetStream())
using (StreamReader streamReader = new StreamReader(networkStream))
{
string message = streamReader.ReadToEnd();
Console.WriteLine("Message: " + message.Length + " bytes");
}
});
thread.Start();
}
catch (SocketException se)
{
Console.WriteLine($"{se.Message} ({se.ErrorCode})");
throw;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
else
{
Thread.Sleep(100);
}
}
}
This is the code I use to send streams (client-side):
public void StartTcpClient()
{
try
{
System.Net.Sockets.TcpClient tcpClient = new();
tcpClient.Connect(
"127.0.0.1",
15001);
NetworkStream networkStream = tcpClient.GetStream();
byte[] message = "This is and example."u8.ToArray();
networkStream.Write(message, 0, message.Length);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
My problem is in the line TcpClient tcpClient = listener.AcceptTcpClient()
; when I start the client, a connection is established, but listener.AcceptTcpClient()
always returns null. No errors or exceptions are thrown;, the code starts the next iteration.
Any idea?