Reputation: 81342
My TCPListener is configured like this:
this.tcpListener = new TcpListener(IPAddress.Any, config.portNum);
I then (using threading) setup a listener function like this:
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
ThreadStart starter = delegate { HandleClientComm(client, this.DBGrid); };
Thread thread = new Thread(starter);
thread.Start();
}
}
First time around it works, 2nd time I fire this , I get this error message:
Only one usage of each socket address (protocol/network address/port) is normally permitted
Inside the thread there is a call to close:
tcpClient.Close();
But it doesn't seem to free the port up, any suggestions?
Upvotes: 1
Views: 451
Reputation: 19976
If you call to ListenForClients
repeatedly, that is the source of your problem, not that client connection doesn't Close()
correctly.
Traditionally, one thread would handle opening main socket and accepting 'child' connection sockets. So your ListenForClients
should be in the main server thread, and called only once per application.
SOME MORE INFO:
this.tcpListener.Start();
creates a listening socked at the port you specified. With every client connecting,
TcpClient client = this.tcpListener.AcceptTcpClient();
line will create a NEW socket that is connected and is on a totally different port. So by closing your client, you don't release your main socket at all.
From http://en.wikipedia.org/wiki/Internet_socket#Socket_states_and_the_client-server_model
Computer processes that provide application services are called servers, and create sockets on start up that are in listening state. These sockets are waiting for initiatives from client programs. For a listening TCP socket, the remote address presented by netstat may be denoted 0.0.0.0 and the remote port number 0.
A TCP server may serve several clients concurrently, by creating a child process for each client and establishing a TCP connection between the child process and the client. Unique dedicated sockets are created for each connection. These are in established state, when a socket-to-socket virtual connection or virtual circuit (VC), also known as a TCP session, is established with the remote socket, providing a duplex byte stream.
Upvotes: 2
Reputation: 8008
The problem is with tcpListener.Start(). You are not allowed to have 2 listeners on the same port. The ListenForClients method should be called only once in your application
Upvotes: 2