Search code examples
c#.netsocketstcpclienttcplistener

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


So the way I start my server is like this

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

The idea here is that I want to seperate the Server from the Client connecting to the server.. So I'll have that class to accept GameClients where as the actual GameClient deals with the networkstream.

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

I then connect with a client like so

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

}

And when I start the server, it says "Waiting for a connection... " and then I start the Client, and the client connects and it says "Connected to the server!" but the server never executes this line

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

Why is that? And how do I properly make it execute that line?


Solution

  • You are giving to the TcpClient the same ip/port for the local endpoint and the remote endpoint:

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

    That makes the socket to connect to itself (you can test it, send something using the stream and read from it, you will receive the message back). Just remove the local endpoint from the client and you will be good to go:

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