Connecting to a TcpListener on a different thread, same process

I'm trying to unit test some comm. code over TCP in C#. I've created a quick thread that stands up a TcpListener. Each time the TcpClient tries to connect I get an "Only one usage of each socket address (protocol/network address/port) is normally permitted" exception. Can you not host on and connect to the same port in the same process?

    [Test]
    public void Foo()
    {
        Thread listenerThread = new Thread(TcpListenerThread);

        listenerThread.Start();

        Thread.Sleep(5000);

        TcpClient client = new TcpClient(new IPEndPoint(IPAddress.Loopback, 1234));        
    }

    private void TcpListenerThread()
    {
        TcpListener listener = new TcpListener(IPAddress.Any, 1234);
        listener.Start();
        TcpClient socket = listener.AcceptTcpClient();
        StreamWriter writer = new StreamWriter(socket.GetStream());

        writer.Write(File.ReadAllBytes("../../random file.txt"));

    }

Answers


You are using wrong constructor of the TcpClient - this one binds the client to local address and port, so you end up with both the listener and the client trying to grab 127.0.0.1:1234. Use the TcpClient( String, int ) constructor.


Need Your Help

Request.URL for localhost and live site

c# asp.net .net request

I have my local host and a live site. I have a url and if its in localhost the url should go localhost/site/thank_you.aspx and if its live http://mylivesite.com/thank_you.aspx

trimming a string in php

php string if-statement trim equality

i'm still quite new to programming, so please excuse me.