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);
TcpClie开发者_如何学Cnt 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"));
}
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.
精彩评论