473,725 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Closing a C# socket does not release port

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(AddressF amily.InterNetw ork,
SocketType.Stre am,
ProtocolType.Tc p);

socket.SetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.DontLinger,
true);

IPEndPoint endPoint = new IPEndPoint(
System.Net.IPAd dress.Parse(soc ketConfig.Addre ss),
socketConfig.Po rt);

socket.Bind(end Point);
socket.Listen(M AX_NUM_CONNECTI ONS);

serverConnectTh read = new Thread(ServerCo nnectThread);
serverConnectTh read.Start();
}

public void Close()
{
socket.Close();
socket = null;
}

protected virtual void ServerConnectTh read()
{
IAsyncResult result;
while (true)
{
if (socket != null && socket.IsBound)
{
try
{
result = socket.BeginAcc ept(new
AsyncCallback(S erverAcceptConn ection), socket);
}
catch (Exception exception)
{
Close();
break;
}
}
else
{
break;
}
// Wait for the EndAccept before issuing a new BeginAccept
result.AsyncWai tHandle.WaitOne ();
}
}

Nov 9 '07 #1
4 16141
I don't see anything that is odd about how you are opening and closing
the socket (although what you are doing with the Socket that is returned
from the call to EndAccept isn't shown, I'm sure you call Close on that, but
that shouldn't affect the main socket anyways).

What I am curious about is why you are calling BeginAccept in the first
place. You are waiting on an event in the thread which I am sure you are
setting after you perform the callback where you call EndAccept. Why not
just call Accept in your thread, do your work and be done with it?

Also, are you making calls to Open from multiple threads? If you are,
then I imagine that you could have a race condition where you are creating a
new socket without closing the old one, and since the old socket is still
bound to the port, getting the exception.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"O.B." <fu******@bells outh.netwrote in message
news:11******** **************@ d55g2000hsg.goo glegroups.com.. .
>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(AddressF amily.InterNetw ork,
SocketType.Stre am,
ProtocolType.Tc p);

socket.SetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.DontLinger,
true);

IPEndPoint endPoint = new IPEndPoint(
System.Net.IPAd dress.Parse(soc ketConfig.Addre ss),
socketConfig.Po rt);

socket.Bind(end Point);
socket.Listen(M AX_NUM_CONNECTI ONS);

serverConnectTh read = new Thread(ServerCo nnectThread);
serverConnectTh read.Start();
}

public void Close()
{
socket.Close();
socket = null;
}

protected virtual void ServerConnectTh read()
{
IAsyncResult result;
while (true)
{
if (socket != null && socket.IsBound)
{
try
{
result = socket.BeginAcc ept(new
AsyncCallback(S erverAcceptConn ection), socket);
}
catch (Exception exception)
{
Close();
break;
}
}
else
{
break;
}
// Wait for the EndAccept before issuing a new BeginAccept
result.AsyncWai tHandle.WaitOne ();
}
}
Nov 9 '07 #2
Only one thread is calling the Open operation.

I'm using BeginAccept because it starts a new thread when a connection
is made. The operation specified within BeginAccept goes into a loop
of receiving data from the socket. Granted, I could use "Accept"
instead and create a new thread myself each time. Unless I'm
mistaken, the two approaches do the exact same thing.

In one of my test cases, the socket is opened, closed, and
dereference. The test sleeps 2 seconds and repeats the cycle two more
times. A connection is never made to the socket. In 20% of the
executions, I encounter a socket exception when trying to open the
socket because the port is still in use.


On Nov 9, 11:17 am, "Nicholas Paldino [.NET/C# MVP]"
<m...@spam.guar d.caspershouse. comwrote:
I don't see anything that is odd about how you are opening and closing
the socket (although what you are doing with the Socket that is returned
from the call to EndAccept isn't shown, I'm sure you call Close on that, but
that shouldn't affect the main socket anyways).

What I am curious about is why you are calling BeginAccept in the first
place. You are waiting on an event in the thread which I am sure you are
setting after you perform the callback where you call EndAccept. Why not
just call Accept in your thread, do your work and be done with it?

Also, are you making calls to Open from multiple threads? If you are,
then I imagine that you could have a race condition where you are creating a
new socket without closing the old one, and since the old socket is still
bound to the port, getting the exception.

--
- Nicholas Paldino [.NET/C# MVP]
- m...@spam.guard .caspershouse.c om

"O.B." <funkj...@bells outh.netwrote in message

news:11******** **************@ d55g2000hsg.goo glegroups.com.. .
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(AddressF amily.InterNetw ork,
SocketType.Stre am,
ProtocolType.Tc p);
socket.SetSocke tOption(SocketO ptionLevel.Sock et,
SocketOptionNam e.DontLinger,
true);
IPEndPoint endPoint = new IPEndPoint(
System.Net.IPAd dress.Parse(soc ketConfig.Addre ss),
socketConfig.Po rt);
socket.Bind(end Point);
socket.Listen(M AX_NUM_CONNECTI ONS);
serverConnectTh read = new Thread(ServerCo nnectThread);
serverConnectTh read.Start();
}
public void Close()
{
socket.Close();
socket = null;
}
protected virtual void ServerConnectTh read()
{
IAsyncResult result;
while (true)
{
if (socket != null && socket.IsBound)
{
try
{
result = socket.BeginAcc ept(new
AsyncCallback(S erverAcceptConn ection), socket);
}
catch (Exception exception)
{
Close();
break;
}
}
else
{
break;
}
// Wait for the EndAccept before issuing a new BeginAccept
result.AsyncWai tHandle.WaitOne ();
}
}

Nov 9 '07 #3
On 2007-11-09 09:17:33 -0800, "Nicholas Paldino [.NET/C# MVP]"
<mv*@spam.guard .caspershouse.c omsaid:
I don't see anything that is odd about how you are opening and
closing the socket (although what you are doing with the Socket that is
returned from the call to EndAccept isn't shown, I'm sure you call
Close on that, but that shouldn't affect the main socket anyways).

What I am curious about is why you are calling BeginAccept in the
first place. You are waiting on an event in the thread which I am sure
you are setting after you perform the callback where you call
EndAccept. Why not just call Accept in your thread, do your work and
be done with it?
Agreed. Or alternatively, forget the loop in ServerConnectTh read()
(and for that matter, probably forget the "server connect thread"
altogether) and just call BeginAccept() again from within the EndAccept
callback method. This is a more typical use of the async methods.
Also, are you making calls to Open from multiple threads? If you
are, then I imagine that you could have a race condition where you are
creating a new socket without closing the old one, and since the old
socket is still bound to the port, getting the exception.
In addition, be aware that a listening socket simply is not normally
removed right away when closed. See "TIME_WAIT" for more details.
Even in perfectly working code, with or without .NET, it's not uncommon
to have to wait some period of time before you can bind a new socket to
a previously used address.

See SocketOptionNam e.ReuseAddress for a workaround.

Pete

Nov 9 '07 #4
On 2007-11-09 09:36:06 -0800, "O.B." <fu******@bells outh.netsaid:
Only one thread is calling the Open operation.

I'm using BeginAccept because it starts a new thread when a connection
is made. The operation specified within BeginAccept goes into a loop
of receiving data from the socket. Granted, I could use "Accept"
instead and create a new thread myself each time. Unless I'm
mistaken, the two approaches do the exact same thing.
Ouch. Don't do that. At the very least, you'll run out of thread pool
threads. It's possible that you'll screw up the async implementation
of the Socket class as well. Make sure that in your callback, you
process the completed operation without delay and return immediately.

If you want to use the async methods, use them correctly. That means
don't create your own threads for the socket. Let the async methods
use the IOCP thread pool as it was designed. In the completion
callback for the various methods (i.e. the methods where you call
EndAccept, EndRecieve, etc.), simply call the "Begin..." method again
to allow a new network operation to occur. After calling EndAccept,
call BeginAccept. After calling EndReceive, call BeginReceive. And so
forth.

If you want to create your own threads for the socket operations, then
don't use the async methods.

Pete

Nov 9 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
9285
by: simon place | last post by:
Spent some very frustrating hours recoding to find a way of closing a server socket, i'd not thought it would be any problem, however, after complete failure and as a last resort, i looked at the python wrapper module for sockets, and found that the close command doesn't actually call the underlying close! this didn't seem right, so i added it, and my code now works simply and as expected. def close(self):
8
2080
by: Jim | last post by:
Need some comments from anyone willing to help, please. See the code included below. This compiles with GCC on FreeBSD 4.7. The only point of it is to accept a socket connection. Nothing else has been implemented. It does not work. Everything matches how it should be (according to the man pages on the relevant functions). It also matches line by line with code from another application used as a known to be working reference. ...
2
10818
by: L.J.SONG | last post by:
I use following code to create socket and connect to a server app: /// code ///// Socket connecter = null; IPEndPoint localEp = null; IPEndPoint remoteEp = null; IPHostEntry he = Dns.Resolve("localhost"); IPAddress localAddr = he.AddressList; localEp = new IPEndPoint(localAddr,11000);
3
2826
by: Tom Opgenorth | last post by:
I'm experiencing a problem with sockets, and I'm really hoping someone can help me, please and thank you. I've written a TCP Server, which listens on a port for an incoming connection. When the client connects, the connection is NEVER to be closed by the server. The client will send messages as necessary. After each message the server is to send an acknowledgement back to the client. That is the client's indicator to send the next...
5
4768
by: zxo102 | last post by:
Hi, I am doing a small project using socket server and thread in python. This is first time for me to use socket and thread things. Here is my case. I have 20 socket clients. Each client send a set of sensor data per second to a socket server. The socket server will do two things: 1. write data into a file via bsddb; 2. forward the data to a GUI written in wxpython. I am thinking the code should work as follow (not sure it is feasible)...
6
16222
by: alessandro | last post by:
Hi all, This is my framework for create TCP server listening forever on a port and supporting threads: import SocketServer port = 2222 ip = "192.168.0.4"
2
18363
by: kodart | last post by:
Introduction Performance is the main concern to most server application developers. That’s why many of them anticipate using .NET platform to develop high performance server application regardless of the security features it provides. Microsoft Windows provides a high performance model that uses I/O completion port (IOCP) to process network events. IOCP provides best performance, but difficult to use due to lack of good code samples and...
0
1318
by: Riccardo Di Meo | last post by:
Hi everyone, I'm practicing with embedding python into C code and i have encountered a very strange problem: I'm unable to call the "accept" method of a (correctly created) server socket without receiving a "Segmentation fault" (inside the PyObject_CallMethod). My code <seemsto be correct (at least it's correct enough for me to call .getsockname(), .fileno() and other methods without problems), I'm pretty new to this thing though,...
0
1822
by: FragMagnet | last post by:
Hi all, I've run into a bit of a snag while dealing with asynchronous sockets. What I'm trying to do is set a timeout for which the server will listen for a connection from a client, at which point the object maintaining the server side connection will be disposed of through the use of a delegate. The code is as follows: public Bridge(string args, int inPort) { name = args; surname = args;
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9116
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.