Home > OS >  Why TCPClient doesn't receive text data
Why TCPClient doesn't receive text data

Time:04-03

I have two projects: client and server.

Server code:

static void Main()
{
    var listener = new TcpListener(System.Net.IPAddress.Loopback, 13000);
    listener.Start();

    using (var client = listener.AcceptTcpClient())
    {
        var stream = client.GetStream();
        var textStream = new StreamReader(stream);

        while (true)
        {
            var line = textStream.ReadLine();

            if (line == "") continue;
            if (line == null) continue;

            var clientIp = IPAddress.Parse(line.Split(':').First());
            var clientPort = int.Parse(line.Split(':').Last());
            var response = new LobbyConnectionResponse(StatusCode.OK, "Connected", new List<Player>(), new Leader("J", Guid.NewGuid()));
            SendResponseToClient(clientIp, clientPort, response);
            Console.WriteLine(line);
            Thread.Sleep(lobbyResponseTimeout);
        }
    }

    listener.Stop();
}

static Task SendResponseToClient(IPAddress ip, int port, LobbyConnectionResponse response)
{
    var task = Task.Run(() =>
    {
        using (var tcpClient = new TcpClient())
        {
            tcpClient.Connect(ip, port);
            var stream = tcpClient.GetStream();
            var textStream = new StreamWriter(stream);
            string jsonString = JsonSerializer.Serialize(response);
            textStream.WriteAsync(jsonString);
            stream.FlushAsync();
        }
    });

    return task;
}

Client code:

static void Main()
{
    StartListener();

    using (var client = new TcpClient())
    {
        client.Connect("127.0.0.1", 13000);
        var stream = client.GetStream();
        var textStream = new StreamWriter(stream);
        textStream.WriteLine("127.0.0.1:12000");
        textStream.Flush();
    }

    while(true)
        Thread.Sleep(1000);
    Thread.Sleep(1000);
}

static Task StartListener()
{
    var task = Task.Run(() =>
    {
        var listener = new TcpListener(System.Net.IPAddress.Loopback, 12000);
        listener.Start();
        while (true)
        {
            using (var client = listener.AcceptTcpClient())
            {
                var stream = client.GetStream();
                var textStream = new StreamReader(stream);
                while (true)
                {
                    if (stream.DataAvailable)
                        Console.WriteLine("hfdsgdf");
                    var line = textStream.ReadLine();
                    if (line == null || line == "") continue;
                    var response = (LobbyConnectionResponse)JsonSerializer.Deserialize(stream, typeof(LobbyConnectionResponse));
                    Console.WriteLine(response.Description);
                    Thread.Sleep(100);
                }
            }
            Thread.Sleep(100);
        }
        listener.Stop();
    });
    return task;
}

On the server's console, I had message:"127.0.0.1:12000" but client's console are empty, why client doesn't receive my text data? 0 Exceptions, clients code just looping infinity and every iteration continues because line == null

When I tried to make that on a single port ( server and client), nothing worked. I want that client get my JSON and deserialize it into class instance.

CodePudding user response:

You need to send data through client/stream variable instead of creating a new connection from server to client.

var listener = new TcpListener(System.Net.IPAddress.Loopback, 13000);
listener.Start();
using (var client = listener.AcceptTcpClient())
{
    var stream = client.GetStream();
            
    // send response to client
    byte[] buffer = Encoding.UTF8.GetBytes("foo");
    stream.Write(buffer, 0, buffer.Length);
    stream.Close();
}
  • Related