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?

    public void Foo()
        Thread listenerThread = new Thread(TcpListenerThread);



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

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

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



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 Use the TcpClient( String, int ) constructor.

Need Your Help

Request.URL for localhost and live site

c# .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

trimming a string in php

php string if-statement trim equality

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