I'm trying to connect to a TCP server with .NET's TcpClient
. For testing, the server is on my own machine. It worked initially, but not when I restarted my application.
So I wrote this small bit of code to try connect/disconnect twice and I can't figure out what I'm doing wrong:
const int clientPort = 29501;
const int port = 29500;
using (var client = new TcpClient(new IPEndPoint(IPAddress.Loopback, clientPort)))
client.Connect(IPAddress.Loopback, port);
using (var client = new TcpClient(new IPEndPoint(IPAddress.Loopback, clientPort)))
client.Connect(IPAddress.Loopback, port);
When I run this code, i get a SocketException
:
Only one usage of each socket address (protocol/network address/port) is normally permitted
What am I doing wrong? Shouldn't the using blocks properly release the socket?