2
votes
        int port = 44344;

        var thread = new Thread(
            () =>
            {
                TcpListener listener = null;
                try
                {
                    listener = new TcpListener(IPAddress.Any, port);
                    listener.Start();

                    while (true)
                    {
                        var client = listener.AcceptTcpClient();
                    }
                }
                catch (ThreadInterruptedException)
                { }

                if (listener != null)
                    listener.Stop();
            });
        thread.Start();

        Thread.Sleep(TimeSpan.FromSeconds(1));

        var socket = new Socket(SocketType.Stream, ProtocolType.IP);
        socket.Connect("localhost", port);

This code fails on the last line with "No connection could be made because the target machine actively refused it" exception, when running on my PC. Any ideas what can be the reason and how to fix it?

1
Maybe you call Connect before your thread gets the chance to run. Test by adding a Thread.Sleep before calling connect. - Eser
@Eser, unfortunately no. It haven't changed anything. - user626528
And by using ProtocolType.Tcp? - Eser
@Eser, no success. too. - user626528
Is that code the real code? Pasting it into LINQPad works. Are there firewalls that block localhost to localhost traffic?! - usr

1 Answers

3
votes

The solution was to create the client socket with an AddressFamily parameter specified:

var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);