c# - 如何向服务器发送 "hello"并回复 "hi"?

标签 c# tcpclient tcpserver

使用我的代码,我可以在服务器上读取消息并从客户端写入。但是我无法从服务器写入响应并在客户端读取。

客户端上的代码

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();

服务器上的代码

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();
}

如何让服务端读取数据后回复,让客户端读取这个数据?

最佳答案

因为你正在使用

TcpClient client = tcpListener.AcceptTcpClient();

,可以直接回写给客户端,不需要它自己识别。 如果您使用 Stream.Read().ReadLine() 而不是 .ReadToEnd(),您的代码将实际工作 ReadToEnd() 将永远阻塞网络流,直到流被关闭。参见 this answer类似问题,或来自 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.

如果您在一侧使用 ReadLine(),则需要在另一侧使用 WriteLine() 而不是 Write()。另一种方法是使用调用 Stream.Read() 的循环,直到没有任何内容可读为止。您可以在 AcceptTcpClient() documentation on MSDN 中看到服务器端的完整示例。 .相应的客户端示例在 TcpClient documentation 中.

关于c# - 如何向服务器发送 "hello"并回复 "hi"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5589605/

相关文章:

c# - C++等效于C#Array.Sort

c# - 奇数命名空间声明

c# - 是否可以在不使用 [JsonIgnore] 的情况下忽略 nswag 中的模型属性?

C# + OracleSQL - 不能在 CommandText 中使用参数

c - 用 C 语言向服务器套接字编程发送各种命令

browser - TCP 服务器将数据推送到 Web 浏览器

c# - TCP 客户端/服务器消息未正确发送

java - 如何注意到客户端与服务器断开连接 - JAVA

c# - TCPClient没有网卡能用吗?

python - 如何停止TCP服务器