Reputation: 129
Suppose I used TcpListener to start listen any IP address and port, it works for the first time. But soon after I restart the program, I got this error 'Only one usage of each socket address is normally permitted'. It sounds like I didn't close tcpListener when I exit my program, I did that in Form_closing but didn't works. Later I found a way to solve this problem by changing my port each time, although this could fix problem I need a fix port. Here how my codes look like.
TcpListener tcpListener;
Socket socketClient;
const int PORT_LISTEN_SERVER = 7568;
tcpListener = new TcpListener(IPAddress.Any, PORT_LISTEN_SERVER);
tcpListener.Start(); //Error at this line
socketClient = tcpListener.AcceptSocket();
IPEndPoint ipend = (IPEndPoint)socketClient.RemoteEndPoint;
toolStripLabel1.Text = "Connection from " + IPAddress.Parse(ipend.Address.ToString());
How I close my listener connection
try
{
MessageBox.Show("Try to clean up!");
tcpListener.Stop();
socketClient.Close();
}
catch { MessageBox.Show("Error CleanUp!"); }
Updated: Suppose I changed into function make recursion. To check perhaps tcpListener's stop method could solve this problem. Every time I try to run the function, I'm keep getting Error Message. It seems like stop method could not solve this.
private void BeginListen()
{
try
{
tcpListener = new TcpListener(IPAddress.Any, PORT_LISTEN_SERVER);
tcpListener.Start();
MessageBox.Show("tcpListener is started");
}
catch (Exception ex)
{
MessageBox.Show("Error at: " + ex);
tcpListener.Stop();
BeginListen();
}
Upvotes: 1
Views: 4536
Reputation: 19395
Well,I just solved it myself. Socket.Close is executed before it assign to. – user3138965
Upvotes: 0