为什么我的服务器不响应连接 TcpListener 和 TcpClient 的客户端

Why isn't my server responding to a client connecting TcpListener and TcpClient

所以我启动服务器的方式是这样的

class GameServer
{
    private TcpListener _server;

    public void Run()
    {
        _server = new TcpListener(IPAddress.Any, Constants.Port);
        _server.Start(Constants.Backlog);

        while (true)
        {
            Console.WriteLine("Waiting for a connection... ");
            //Perform a blocking call to accept requests.
            _ = new GameClient(_server.AcceptTcpClient());
        }
    }
}

这里的想法是我想将服务器与连接到服务器的客户端分开。所以我会让 class 接受 GameClients,因为实际的 GameClient 处理网络流。

class GameClient
{
    private TcpClient _client;
    private NetworkStream _stream;

    private byte[] buffer = new byte[Constants.BufferSize];
    private Packet packet;

    public GameClient(TcpClient client)
    {
        packet = new Packet();

        _client = client;
        Console.WriteLine($"[+] Client connected: {_client.Client.RemoteEndPoint}");
        _stream = _client.GetStream();
    }
}

然后我像这样与客户联系

public void Connect()
{
    try
    {
        var client = new TcpClient(localEP: new IPEndPoint(
            IPAddress.Parse(Constants.IpAddress),
            Constants.Port));

        client.Connect(remoteEP: new IPEndPoint(
            IPAddress.Parse(Constants.IpAddress),
            Constants.Port));

        var stream = client.GetStream();

        if (client.Connected)
        {
            Console.WriteLine("Connected to the server!");
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }

}

当我启动服务器时,它显示“正在等待连接...”,然后我启动客户端,客户端连接并显示“已连接到服务器!”但是服务器从不执行这一行

Console.WriteLine($"[+] Client connected: {_client.Client.RemoteEndPoint}");

这是为什么?我如何正确地让它执行该行?

您为本地端点和远程端点向 TcpClient 提供了相同的 ip/port:

var client = new TcpClient(localEP: new IPEndPoint(
        IPAddress.Parse(Constants.IpAddress),
        Constants.Port));

    client.Connect(remoteEP: new IPEndPoint(
        IPAddress.Parse(Constants.IpAddress),
        Constants.Port));

这使得套接字连接到自身(您可以对其进行测试,使用流发送内容并从中读取,您将收到返回的消息)。只需从客户端删除本地端点即可:

var client = new TcpClient();

    client.Connect(remoteEP: new IPEndPoint(
        IPAddress.Parse(Constants.IpAddress),
        Constants.Port));