Search code examples
c#socketstcp

C# socket problems


I connected to PCs with a cable in an attempt to simulate server\client. Server starts listening at specific EndPoint and sometimes later a client connects. All went well and I settled on maximum speed of about 24 Mbps for one connection (port).
So now I reversed the roles and can't get connection Socket.BeginConnect(ServerEndPoint, new AsyncCallback(OnConnectCallback), _ClientSocket) times out and sets localEndpoint to 0.0.0.0

Here is the code for client:

public void ConnectToServer(IPAddress iPAddress, int Port)
    {
        connected.Reset();
        IPEndPoint ServerEndPoint = new IPEndPoint(iPAddress, Port);

        try
        {
            _ClientSocket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _ClientSocket.BeginConnect(ServerEndPoint, new AsyncCallback(OnConnectCallback), _ClientSocket);

            connected.WaitOne();

            // Here I would like to start async receiving but there's no connection
        }
        catch (SocketException)
        {
            // TODO:
        }
    }

private void OnConnectCallback(IAsyncResult result)
    {
        try
        {
            Socket client_StateSocket = (Socket)result.AsyncState;

            client_StateSocket.EndConnect(result);

            /// Here I get 0.0.0.0
            connected.Set();
        }

        catch (SocketException)
        {
            // TODO:
        }
    }

The server is bascialy from MSDN example. It starts listening for incoming connections, goes in perpetual while cycle and sits waiting for Socket.BeginAccept to trigger (but it never does).
I suspected firewall, but the settings look the same on both PCs and works fine in reversed way, so what might be the problem?


Solution

  • When you do development of a Server/Client architecture, it is usually enough to have both run on the same machine and let them talk via the Loopback IP adress. As a general rule the networking code does not care if the other end is on the same computer, the same switch - or the Voyager 2 probe (well, they do care a little as the Latency is quite high).

    If you are having issues in deployment/testing, then with 99% propability you are dealing with a Networking problem, not a programming one. Sometimes there will be some required changes (like exposing the option to set proxy settings). But debugging will be a Networking operation first.

    My first guesses are towards firewalls (including the one built into Windows). And then things that work similar to a firewall, like NAT layers.