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

Home Posts Topics Members FAQ

What is the best way to stop a Socket.BeginAcc ept call?

I've created a class to listen to all interfaces and do a
BeginAccept(). Once it gets a connection, it passes the connected
socket off and stores it in a List. Next, it continues to listen for
more incoming connections and does the BeginAccpet() again. It does
an infinite loop this way. My question is: What is the best way to
stop this? I thought about putting a boolean in there, but then what
if it's still waiting for an incoming connection? Can I just close
the socket?
Here is my code for reference:
public class Listener
{
private Socket m_listener;
private ConnectionCallb ack m_callBack;

public Listener(Connec tionCallback callme)
{
m_callBack = callme;
}

public void AcceptNewConnec tions()
{
this.AcceptNewC onnections(2200 );
}

public void AcceptNewConnec tions(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAd dress.Any, port);
m_listener = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
m_listener.Bind (theEnd);
Console.WriteLi ne("Binding to " +
theEnd.Address. ToString() + " on port " + theEnd.Port.ToS tring());
m_listener.List en(20); //TODO: make this
configurable
Console.WriteLi ne("Now listening");
AsyncCallback callme = new AsyncCallback(A ddWorkerSocket) ;
m_listener.Begi nAccept(callme, m_listener);
}

private void AddWorkerSocket (IAsyncResult ar)
{
Console.WriteLi ne("Got a Connection");
Socket hold = (Socket)ar.Asyn cState;
Socket work = hold.EndAccept( ar);
if (work.Connected )
{
Console.WriteLi ne("Accepted a connection from " +
work.RemoteEndP oint.ToString() );
m_callBack(work );
}
AsyncCallback callMe = new AsyncCallback(A ddWorkerSocket) ;
hold.BeginAccep t(callMe, hold);
}
}

Feb 28 '07 #1
5 12798
On Feb 28, 11:58 am, darthgha...@gma il.com wrote:
I've created a class to listen to all interfaces and do a
BeginAccept(). Once it gets a connection, it passes the connected
socket off and stores it in a List. Next, it continues to listen for
more incoming connections and does the BeginAccpet() again. It does
an infinite loop this way. My question is: What is the best way to
stop this? I thought about putting a boolean in there, but then what
if it's still waiting for an incoming connection? Can I just close
the socket?
It's been a while since I used these APIs but - Yes - I think you can
close the socket. If I recall you will get a "socket closed"
exception so you might want to put a try catch around your
BeginAccept() code...

Feb 28 '07 #2
<
It does an infinite loop this way...
>
Does it bother you? Instead of closing the listening socket, you can put a
limit on the number of client connections and issue BeginAccept() only until
that limit is reached. Normally you would close the listening socket only
after you have no clients connected and done with TCP.

Michael

<da*********@gm ail.comwrote in message
news:11******** **************@ p10g2000cwp.goo glegroups.com.. .
I've created a class to listen to all interfaces and do a
BeginAccept(). Once it gets a connection, it passes the connected
socket off and stores it in a List. Next, it continues to listen for
more incoming connections and does the BeginAccpet() again. It does
an infinite loop this way. My question is: What is the best way to
stop this? I thought about putting a boolean in there, but then what
if it's still waiting for an incoming connection? Can I just close
the socket?
Here is my code for reference:
public class Listener
{
private Socket m_listener;
private ConnectionCallb ack m_callBack;

public Listener(Connec tionCallback callme)
{
m_callBack = callme;
}

public void AcceptNewConnec tions()
{
this.AcceptNewC onnections(2200 );
}

public void AcceptNewConnec tions(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAd dress.Any, port);
m_listener = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
m_listener.Bind (theEnd);
Console.WriteLi ne("Binding to " +
theEnd.Address. ToString() + " on port " + theEnd.Port.ToS tring());
m_listener.List en(20); //TODO: make this
configurable
Console.WriteLi ne("Now listening");
AsyncCallback callme = new AsyncCallback(A ddWorkerSocket) ;
m_listener.Begi nAccept(callme, m_listener);
}

private void AddWorkerSocket (IAsyncResult ar)
{
Console.WriteLi ne("Got a Connection");
Socket hold = (Socket)ar.Asyn cState;
Socket work = hold.EndAccept( ar);
if (work.Connected )
{
Console.WriteLi ne("Accepted a connection from " +
work.RemoteEndP oint.ToString() );
m_callBack(work );
}
AsyncCallback callMe = new AsyncCallback(A ddWorkerSocket) ;
hold.BeginAccep t(callMe, hold);
}
}

Mar 1 '07 #3
On Mar 1, 10:10 am, "Michael Rubinstein"
<mSPAM_REMOVEr@ m®ubinstein.com wrote:
<
It does an infinite loop this way...

Does it bother you? Instead of closing the listening socket, you can put a
limit on the number of client connections and issue BeginAccept() only until
that limit is reached. Normally you would close the listening socket only
after you have no clients connected and done with TCP.

Michael

<darthgha...@gm ail.comwrote in message

news:11******** **************@ p10g2000cwp.goo glegroups.com.. .
I've created a class to listen to all interfaces and do a
BeginAccept(). Once it gets a connection, it passes the connected
socket off and stores it in a List. Next, it continues to listen for
more incoming connections and does the BeginAccpet() again. It does
an infinite loop this way. My question is: What is the best way to
stop this? I thought about putting a boolean in there, but then what
if it's still waiting for an incoming connection? Can I just close
the socket?
Here is my code for reference:
public class Listener
{
private Socket m_listener;
private ConnectionCallb ack m_callBack;
public Listener(Connec tionCallback callme)
{
m_callBack = callme;
}
public void AcceptNewConnec tions()
{
this.AcceptNewC onnections(2200 );
}
public void AcceptNewConnec tions(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAd dress.Any, port);
m_listener = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
m_listener.Bind (theEnd);
Console.WriteLi ne("Binding to " +
theEnd.Address. ToString() + " on port " + theEnd.Port.ToS tring());
m_listener.List en(20); //TODO: make this
configurable
Console.WriteLi ne("Now listening");
AsyncCallback callme = new AsyncCallback(A ddWorkerSocket) ;
m_listener.Begi nAccept(callme, m_listener);
}
private void AddWorkerSocket (IAsyncResult ar)
{
Console.WriteLi ne("Got a Connection");
Socket hold = (Socket)ar.Asyn cState;
Socket work = hold.EndAccept( ar);
if (work.Connected )
{
Console.WriteLi ne("Accepted a connection from " +
work.RemoteEndP oint.ToString() );
m_callBack(work );
}
AsyncCallback callMe = new AsyncCallback(A ddWorkerSocket) ;
hold.BeginAccep t(callMe, hold);
}
}
I was hoping for an infinite loop, sort of. I would like this to
become a window's service, so I want to listen for incoming
connections until the service is stopped. I was really wondering if
anyone was familiar with the "best way" to stop from this sort of
loop. I have modified the code slightly so that when the service
stops, the list of sockets is looped through. While looping through
the sockets, I call Socket.Close() in order to try to clean up my
mess. It seems to work without throwing any exceptions, but I am just
wondering if this is the right way to do things.
Thanks again for your time and comments. Here is the modified code:
public delegate void ConnectionCallb ack(Socket sockMe);
public class Controller
{
private Listener m_listen;
private List<Socketm_wo kerList;
//need a connection
//private List<Connection connectList;

public Controller()
{
m_wokerList = new List<Socket>(20 ); //TODO: make
this configurable
}

public void Start()
{
m_listen = new Listener(new
ConnectionCallb ack(this.AddSoc ketToList));
m_listen.Accept NewConnections( );
}

public void AddSocketToList (Socket sock)
{
Console.WriteLi ne("Got a socket and adding it to the list
of workers");
m_wokerList.Add (sock);
Console.WriteLi ne("There are now " +
m_wokerList.Cou nt.ToString() + " sockets in the list.");
if (m_wokerList[m_wokerList.Cou nt - 1].Connected)
{
Console.WriteLi ne("The last socket is connected to" +
m_wokerList[m_wokerList.Cou nt - 1].RemoteEndPoint .ToString());
}
else
{
Console.WriteLi ne("The last socket is NOT connected");
}

}

public void Stop()
{
foreach (Socket closeSock in m_wokerList)
{
closeSock.Close ();
}
m_listen.StopLi stening();
}
}
public class Listener
{
private Socket m_listener;
private ConnectionCallb ack m_callBack;

public Listener(Connec tionCallback callme)
{
m_callBack = callme;
}

public void AcceptNewConnec tions()
{
this.AcceptNewC onnections(2200 );
}

public void AcceptNewConnec tions(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAd dress.Any, port);
m_listener = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
m_listener.Bind (theEnd);
Console.WriteLi ne("Binding to " +
theEnd.Address. ToString() + " on port " + theEnd.Port.ToS tring());
m_listener.List en(20); //TODO: make this
configurable
Console.WriteLi ne("Now listening");
AsyncCallback callme = new AsyncCallback(A ddWorkerSocket) ;
m_listener.Begi nAccept(callme, m_listener);
}

private void AddWorkerSocket (IAsyncResult ar)
{
Console.WriteLi ne("Got a Connection");
Socket hold = (Socket)ar.Asyn cState;
Socket work = hold.EndAccept( ar);
if (work.Connected )
{
Console.WriteLi ne("Accepted a connection from " +
work.RemoteEndP oint.ToString() );
m_callBack(work );
}
AsyncCallback callMe = new AsyncCallback(A ddWorkerSocket) ;
hold.BeginAccep t(callMe, hold);
}

public void StopListening()
{
m_listener.Clos e();
}
}

Mar 2 '07 #4
I think you worry about wrong things. To begin with, why do initialize the
listener passing a delegate? You can certainly do so, but it will only make
your code more obscure.
>
I was really wondering if anyone was familiar with the "best way" to stop
from this sort of loop
>
there must be a button or a switch on the front panel of your PC, or you can
just pull the AC cord. Seriously, whatever loops your program runs, or the
framework runs on your program behalf, will be exited once you stop the
service. If you want a graceful exit, then stop accepting new connections,
close all worker sockets, close the listener socket. The best way of
disconnecting connected clients is calling ShutDown() followed by
BeginDisconnect () end call socket.Close() from EndDisconnect() .
BeginDisconnect ()/EndDisconnect() are supported only on XP and higher. You
could get away with socket.Shutdown () / socket.Close() with proper error
interception in callback methods.
>
I would like this to become a window's service, so I want to listen for
incoming connections until the service is stopped.
>
in my opinion this would require much cleaner code.

Michael

<da*********@gm ail.comwrote in message
news:11******** *************@8 g2000cwh.google groups.com...
On Mar 1, 10:10 am, "Michael Rubinstein"
<mSPAM_REMOVEr@ m®ubinstein.com wrote:
<
It does an infinite loop this way...

Does it bother you? Instead of closing the listening socket, you can put a
limit on the number of client connections and issue BeginAccept() only
until
that limit is reached. Normally you would close the listening socket only
after you have no clients connected and done with TCP.

Michael

<darthgha...@gm ail.comwrote in message

news:11******** **************@ p10g2000cwp.goo glegroups.com.. .
I've created a class to listen to all interfaces and do a
BeginAccept(). Once it gets a connection, it passes the connected
socket off and stores it in a List. Next, it continues to listen for
more incoming connections and does the BeginAccpet() again. It does
an infinite loop this way. My question is: What is the best way to
stop this? I thought about putting a boolean in there, but then what
if it's still waiting for an incoming connection? Can I just close
the socket?
Here is my code for reference:
public class Listener
{
private Socket m_listener;
private ConnectionCallb ack m_callBack;
public Listener(Connec tionCallback callme)
{
m_callBack = callme;
}
public void AcceptNewConnec tions()
{
this.AcceptNewC onnections(2200 );
}
public void AcceptNewConnec tions(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAd dress.Any, port);
m_listener = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
m_listener.Bind (theEnd);
Console.WriteLi ne("Binding to " +
theEnd.Address. ToString() + " on port " + theEnd.Port.ToS tring());
m_listener.List en(20); //TODO: make this
configurable
Console.WriteLi ne("Now listening");
AsyncCallback callme = new AsyncCallback(A ddWorkerSocket) ;
m_listener.Begi nAccept(callme, m_listener);
}
private void AddWorkerSocket (IAsyncResult ar)
{
Console.WriteLi ne("Got a Connection");
Socket hold = (Socket)ar.Asyn cState;
Socket work = hold.EndAccept( ar);
if (work.Connected )
{
Console.WriteLi ne("Accepted a connection from " +
work.RemoteEndP oint.ToString() );
m_callBack(work );
}
AsyncCallback callMe = new AsyncCallback(A ddWorkerSocket) ;
hold.BeginAccep t(callMe, hold);
}
}
I was hoping for an infinite loop, sort of. I would like this to
become a window's service, so I want to listen for incoming
connections until the service is stopped. I was really wondering if
anyone was familiar with the "best way" to stop from this sort of
loop. I have modified the code slightly so that when the service
stops, the list of sockets is looped through. While looping through
the sockets, I call Socket.Close() in order to try to clean up my
mess. It seems to work without throwing any exceptions, but I am just
wondering if this is the right way to do things.
Thanks again for your time and comments. Here is the modified code:
public delegate void ConnectionCallb ack(Socket sockMe);
public class Controller
{
private Listener m_listen;
private List<Socketm_wo kerList;
//need a connection
//private List<Connection connectList;

public Controller()
{
m_wokerList = new List<Socket>(20 ); //TODO: make
this configurable
}

public void Start()
{
m_listen = new Listener(new
ConnectionCallb ack(this.AddSoc ketToList));
m_listen.Accept NewConnections( );
}

public void AddSocketToList (Socket sock)
{
Console.WriteLi ne("Got a socket and adding it to the list
of workers");
m_wokerList.Add (sock);
Console.WriteLi ne("There are now " +
m_wokerList.Cou nt.ToString() + " sockets in the list.");
if (m_wokerList[m_wokerList.Cou nt - 1].Connected)
{
Console.WriteLi ne("The last socket is connected to" +
m_wokerList[m_wokerList.Cou nt - 1].RemoteEndPoint .ToString());
}
else
{
Console.WriteLi ne("The last socket is NOT connected");
}

}

public void Stop()
{
foreach (Socket closeSock in m_wokerList)
{
closeSock.Close ();
}
m_listen.StopLi stening();
}
}
public class Listener
{
private Socket m_listener;
private ConnectionCallb ack m_callBack;

public Listener(Connec tionCallback callme)
{
m_callBack = callme;
}

public void AcceptNewConnec tions()
{
this.AcceptNewC onnections(2200 );
}

public void AcceptNewConnec tions(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAd dress.Any, port);
m_listener = new Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p);
m_listener.Bind (theEnd);
Console.WriteLi ne("Binding to " +
theEnd.Address. ToString() + " on port " + theEnd.Port.ToS tring());
m_listener.List en(20); //TODO: make this
configurable
Console.WriteLi ne("Now listening");
AsyncCallback callme = new AsyncCallback(A ddWorkerSocket) ;
m_listener.Begi nAccept(callme, m_listener);
}

private void AddWorkerSocket (IAsyncResult ar)
{
Console.WriteLi ne("Got a Connection");
Socket hold = (Socket)ar.Asyn cState;
Socket work = hold.EndAccept( ar);
if (work.Connected )
{
Console.WriteLi ne("Accepted a connection from " +
work.RemoteEndP oint.ToString() );
m_callBack(work );
}
AsyncCallback callMe = new AsyncCallback(A ddWorkerSocket) ;
hold.BeginAccep t(callMe, hold);
}

public void StopListening()
{
m_listener.Clos e();
}
}
Mar 2 '07 #5
>I think you worry about wrong things. To begin with, why do initialize the
>listener passing a delegate? You can certainly do so, but it will only make
your code more obscure.
So what should I worry about? I'm new at this and could use all the
help I can get.
>I would like this to become a window's service, so I want to listen for
incoming connections until the service is stopped.
in my opinion this would require much cleaner code.
Do you have examples of what would be cleaner code? Since I am new at
this, I'm not aware of the mistakes I've made that you are
referencing.
Does anyone else have any suggestions?

Thanks for your time,
Chris

Mar 7 '07 #6

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

Similar topics

5
6027
by: Droopy Toon | last post by:
Hi, I am using asynchronous socket (BeginAccept for example). I tried to name each thread I am using but threads created by asynchronous Socket functions (like BeginAccept) creates "anonymous" threads. I named the thread (see sample code below) in Accept callback started by BeginAccept but all connections accepted run in a thread that has the same name ! So, even a new thread is not started by BeginAccept, even my naming is
0
341
by: Joachim | last post by:
When closing down my server I get the following exception An unhandled exception of type 'System.InvalidOperationException' occurred in system.dll Additional information: AcceptCallback I beleive that it is the asynchronous BeginAccept call which causes the
1
6284
by: Chris Morse | last post by:
WARNING: Verbosity: skip to the very bottom paragraph for succinct version of my question.) Hi- I can't seem to find an answer to this. I am playing around with a variation of the ".NET Framework Developer's Guide" (in the MSDN docs) "Using an Asynchronous Server Socket" sample. As usual with docs like this, the example isn't very good. I had to
1
6678
by: Alper AKCAYOZ | last post by:
Hello, I have developped asynchronous socket communication with blocking Socket commands (accept, connect, send, receive) by using threads on Windows .NET Forms. It is working properly. Now I want to code the similar program with Asynchronous Socket commands of .NET using Managed C++ on Windows .NET Forms. My problem is with delegates. I have to use "static" methods as parameter in delegate constructor like below:...
1
1499
by: =?Utf-8?B?aXdkdTE1?= | last post by:
Hi, i have a socket that i use to listen for a connection. there can be any number of connections. when testing my socket, it sees the first connection, then no others. i call the BeginAccept() method again, but it doesnt see any other connections. heres the code... Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ep As New IPEndPoint(ipHome, PORT)
9
2298
by: =?Utf-8?B?aXdkdTE1?= | last post by:
Hi, im making an AIM like server using TCP sockets, however i found a big issue. when a socket is connected to (socket.EndAccept(ar)), its already bound to a Port. since its bound, i cannot change its access to non exclusive, but i need this port to still be open because i may need another socket to connect on this port as well. how can i achieve this? -- -iwdu15
10
5183
by: ThunderMusic | last post by:
Hi, I'm currently working with sockets. I accept connections using m_mySocket.Listen(BackLogCount); But when I want to stop listening, I shutdown all my clients and call m_mySocket.Close(), but it always raise a OnConnect event (actually, it calls the callback function as if there was a new connection attempt) and I receive a ObjectDisposedException as soon as I do m_mySocket.EndAccept. Does anyone have any idea of what I could do about...
4
16141
by: O.B. | last post by:
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:
4
3331
by: setiarakesh | last post by:
I have designed a socket Server and developed asynchronous server . It is working fine with 60 Clients which are connecting to ths Server running at Machine (2 GB RAM and OS is Windows 2003 Server)having IP which is Mapped with static IP and Port in firewall . The Programme is working fine with 60 clients and rate if incoing data on the server is 5 -6 string of 1024 byte size are being saved in DataBase. When i try to connect ...
0
8888
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
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
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
9176
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
8097
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
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...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.