O
O.B.
I have a socket configured as TCP and running as a listener. When I
close socket, it doesn't always free up the port immediately. Even
when no connections have been made to it. So when I open the socket
again, the bind fails because the port is still in use. When I
execute the code in "debug" mode, the problem never occurs. When I
execute the same code in release mode, the problem appears about 20%
of the time.
Here's the code:
protected Socket socket = null;
public void Open()
{
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.DontLinger,
true);
IPEndPoint endPoint = new IPEndPoint(
System.Net.IPAddress.Parse(socketConfig.Address),
socketConfig.Port);
socket.Bind(endPoint);
socket.Listen(MAX_NUM_CONNECTIONS);
serverConnectThread = new Thread(ServerConnectThread);
serverConnectThread.Start();
}
public void Close()
{
socket.Close();
socket = null;
}
protected virtual void ServerConnectThread()
{
IAsyncResult result;
while (true)
{
if (socket != null && socket.IsBound)
{
try
{
result = socket.BeginAccept(new
AsyncCallback(ServerAcceptConnection), socket);
}
catch (Exception exception)
{
Close();
break;
}
}
else
{
break;
}
// Wait for the EndAccept before issuing a new BeginAccept
result.AsyncWaitHandle.WaitOne();
}
}
close socket, it doesn't always free up the port immediately. Even
when no connections have been made to it. So when I open the socket
again, the bind fails because the port is still in use. When I
execute the code in "debug" mode, the problem never occurs. When I
execute the same code in release mode, the problem appears about 20%
of the time.
Here's the code:
protected Socket socket = null;
public void Open()
{
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.DontLinger,
true);
IPEndPoint endPoint = new IPEndPoint(
System.Net.IPAddress.Parse(socketConfig.Address),
socketConfig.Port);
socket.Bind(endPoint);
socket.Listen(MAX_NUM_CONNECTIONS);
serverConnectThread = new Thread(ServerConnectThread);
serverConnectThread.Start();
}
public void Close()
{
socket.Close();
socket = null;
}
protected virtual void ServerConnectThread()
{
IAsyncResult result;
while (true)
{
if (socket != null && socket.IsBound)
{
try
{
result = socket.BeginAccept(new
AsyncCallback(ServerAcceptConnection), socket);
}
catch (Exception exception)
{
Close();
break;
}
}
else
{
break;
}
// Wait for the EndAccept before issuing a new BeginAccept
result.AsyncWaitHandle.WaitOne();
}
}