How to send a “hello” to server and reply a “hi”?

限于喜欢 提交于 2019-12-14 01:23:16

问题


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?


回答1:


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.




回答2:


Cheesy, inneficient, but does the trick on a one-time throwaway program:

  • Client: In the stream, include the port and IP address it wishes to receive the response from.
  • Client: Create a listener for that port and IP.
  • Server: Read in the port/IP info and in turn connect, then send the reply stream.

However, this is a great place to start, look into Sockets class for proper bi-directional communication.



来源:https://stackoverflow.com/questions/5589605/how-to-send-a-hello-to-server-and-reply-a-hi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!