Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a "hello" to server and reply a "hi"?

With my code I can read a message on the server and write from the client. But I am not being able to write a response from the server and read in the client.

The code on the client

var cli = new TcpClient();

cli.Connect("127.0.0.1", 6800);

string data = String.Empty;

using (var ns = cli.GetStream())
{
    using (var sw = new StreamWriter(ns))
    {
        sw.Write("Hello");
        sw.Flush();

        //using (var sr = new StreamReader(ns))
        //{
        //    data = sr.ReadToEnd();
        //}
    }
}

cli.Close();

The code on the server

tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();

while (run)
{
    var client = tcpListener.AcceptTcpClient();

    string data = String.Empty;

    using (var ns = client.GetStream())
    {
        using (var sr = new StreamReader(ns))
        {
            data = sr.ReadToEnd();

            //using (var sw = new StreamWriter(ns))
            //{
            //    sw.WriteLine("Hi");
            //    sw.Flush();
            //}
        }
    }
    client.Close();
}

How can I make the server reply after reading the data and make the client read this data?

like image 679
BrunoLM Avatar asked Nov 28 '25 15:11

BrunoLM


1 Answers

Since you are using

TcpClient client = tcpListener.AcceptTcpClient();

, you can write back to the client directly without needing it to self-identify. The code you have will actually work if you use Stream.Read() or .ReadLine() instead of .ReadToEnd(). ReadToEnd() will block forever on a network stream, until the stream is closed. See this answer to a similar question, or from MSDN,

ReadToEnd assumes that the stream knows when it has reached an end. For interactive protocols in which the server sends data only when you ask for it and does not close the connection, ReadToEnd might block indefinitely because it does not reach an end, and should be avoided.

If you use ReadLine() at one side, you will need to use WriteLine() - not Write() - at the other side. The alternative is to use a loop that calls Stream.Read() until there is nothing left to read. You can see a full example of this for the server side in the AcceptTcpClient() documentation on MSDN. The corresponding client example is in the TcpClient documentation.

like image 178
Kimberly Avatar answered Dec 01 '25 04:12

Kimberly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!