为什么 TCPClient 收不到文本数据

Why TCPClient doesn't receive text data

我有两个项目:客户端和服务器。

服务器代码:

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

客户代码:

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

在服务器的控制台上,我有消息:“127.0.0.1:12000”但是客户端的控制台是空的,为什么客户端没有收到我的文本数据? 0 异常,客户端代码只是无限循环并且每次迭代都会继续,因为行 == null

当我尝试在单个端口(服务器和客户端)上创建它时,没有任何效果。我希望客户端获取我的 JSON 并将其反序列化为 class 实例。

您需要通过 client/stream 变量发送数据,而不是创建从服务器到客户端的新连接。

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