473,396 Members | 1,768 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

What is the best way to stop a Socket.BeginAccept 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 ConnectionCallback m_callBack;

public Listener(ConnectionCallback callme)
{
m_callBack = callme;
}

public void AcceptNewConnections()
{
this.AcceptNewConnections(2200);
}

public void AcceptNewConnections(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAddress.Any, port);
m_listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
m_listener.Bind(theEnd);
Console.WriteLine("Binding to " +
theEnd.Address.ToString() + " on port " + theEnd.Port.ToString());
m_listener.Listen(20); //TODO: make this
configurable
Console.WriteLine("Now listening");
AsyncCallback callme = new AsyncCallback(AddWorkerSocket);
m_listener.BeginAccept(callme, m_listener);
}

private void AddWorkerSocket(IAsyncResult ar)
{
Console.WriteLine("Got a Connection");
Socket hold = (Socket)ar.AsyncState;
Socket work = hold.EndAccept(ar);
if (work.Connected)
{
Console.WriteLine("Accepted a connection from " +
work.RemoteEndPoint.ToString());
m_callBack(work);
}
AsyncCallback callMe = new AsyncCallback(AddWorkerSocket);
hold.BeginAccept(callMe, hold);
}
}

Feb 28 '07 #1
5 12731
On Feb 28, 11:58 am, darthgha...@gmail.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*********@gmail.comwrote in message
news:11**********************@p10g2000cwp.googlegr oups.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 ConnectionCallback m_callBack;

public Listener(ConnectionCallback callme)
{
m_callBack = callme;
}

public void AcceptNewConnections()
{
this.AcceptNewConnections(2200);
}

public void AcceptNewConnections(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAddress.Any, port);
m_listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
m_listener.Bind(theEnd);
Console.WriteLine("Binding to " +
theEnd.Address.ToString() + " on port " + theEnd.Port.ToString());
m_listener.Listen(20); //TODO: make this
configurable
Console.WriteLine("Now listening");
AsyncCallback callme = new AsyncCallback(AddWorkerSocket);
m_listener.BeginAccept(callme, m_listener);
}

private void AddWorkerSocket(IAsyncResult ar)
{
Console.WriteLine("Got a Connection");
Socket hold = (Socket)ar.AsyncState;
Socket work = hold.EndAccept(ar);
if (work.Connected)
{
Console.WriteLine("Accepted a connection from " +
work.RemoteEndPoint.ToString());
m_callBack(work);
}
AsyncCallback callMe = new AsyncCallback(AddWorkerSocket);
hold.BeginAccept(callMe, hold);
}
}

Mar 1 '07 #3
On Mar 1, 10:10 am, "Michael Rubinstein"
<mSPAM_REMOVEr@m®ubinstein.comwrote:
<
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...@gmail.comwrote in message

news:11**********************@p10g2000cwp.googlegr oups.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 ConnectionCallback m_callBack;
public Listener(ConnectionCallback callme)
{
m_callBack = callme;
}
public void AcceptNewConnections()
{
this.AcceptNewConnections(2200);
}
public void AcceptNewConnections(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAddress.Any, port);
m_listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
m_listener.Bind(theEnd);
Console.WriteLine("Binding to " +
theEnd.Address.ToString() + " on port " + theEnd.Port.ToString());
m_listener.Listen(20); //TODO: make this
configurable
Console.WriteLine("Now listening");
AsyncCallback callme = new AsyncCallback(AddWorkerSocket);
m_listener.BeginAccept(callme, m_listener);
}
private void AddWorkerSocket(IAsyncResult ar)
{
Console.WriteLine("Got a Connection");
Socket hold = (Socket)ar.AsyncState;
Socket work = hold.EndAccept(ar);
if (work.Connected)
{
Console.WriteLine("Accepted a connection from " +
work.RemoteEndPoint.ToString());
m_callBack(work);
}
AsyncCallback callMe = new AsyncCallback(AddWorkerSocket);
hold.BeginAccept(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 ConnectionCallback(Socket sockMe);
public class Controller
{
private Listener m_listen;
private List<Socketm_wokerList;
//need a connection
//private List<ConnectionconnectList;

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

public void Start()
{
m_listen = new Listener(new
ConnectionCallback(this.AddSocketToList));
m_listen.AcceptNewConnections();
}

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

}

public void Stop()
{
foreach (Socket closeSock in m_wokerList)
{
closeSock.Close();
}
m_listen.StopListening();
}
}
public class Listener
{
private Socket m_listener;
private ConnectionCallback m_callBack;

public Listener(ConnectionCallback callme)
{
m_callBack = callme;
}

public void AcceptNewConnections()
{
this.AcceptNewConnections(2200);
}

public void AcceptNewConnections(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAddress.Any, port);
m_listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
m_listener.Bind(theEnd);
Console.WriteLine("Binding to " +
theEnd.Address.ToString() + " on port " + theEnd.Port.ToString());
m_listener.Listen(20); //TODO: make this
configurable
Console.WriteLine("Now listening");
AsyncCallback callme = new AsyncCallback(AddWorkerSocket);
m_listener.BeginAccept(callme, m_listener);
}

private void AddWorkerSocket(IAsyncResult ar)
{
Console.WriteLine("Got a Connection");
Socket hold = (Socket)ar.AsyncState;
Socket work = hold.EndAccept(ar);
if (work.Connected)
{
Console.WriteLine("Accepted a connection from " +
work.RemoteEndPoint.ToString());
m_callBack(work);
}
AsyncCallback callMe = new AsyncCallback(AddWorkerSocket);
hold.BeginAccept(callMe, hold);
}

public void StopListening()
{
m_listener.Close();
}
}

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*********@gmail.comwrote in message
news:11*********************@8g2000cwh.googlegroup s.com...
On Mar 1, 10:10 am, "Michael Rubinstein"
<mSPAM_REMOVEr@m®ubinstein.comwrote:
<
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...@gmail.comwrote in message

news:11**********************@p10g2000cwp.googlegr oups.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 ConnectionCallback m_callBack;
public Listener(ConnectionCallback callme)
{
m_callBack = callme;
}
public void AcceptNewConnections()
{
this.AcceptNewConnections(2200);
}
public void AcceptNewConnections(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAddress.Any, port);
m_listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
m_listener.Bind(theEnd);
Console.WriteLine("Binding to " +
theEnd.Address.ToString() + " on port " + theEnd.Port.ToString());
m_listener.Listen(20); //TODO: make this
configurable
Console.WriteLine("Now listening");
AsyncCallback callme = new AsyncCallback(AddWorkerSocket);
m_listener.BeginAccept(callme, m_listener);
}
private void AddWorkerSocket(IAsyncResult ar)
{
Console.WriteLine("Got a Connection");
Socket hold = (Socket)ar.AsyncState;
Socket work = hold.EndAccept(ar);
if (work.Connected)
{
Console.WriteLine("Accepted a connection from " +
work.RemoteEndPoint.ToString());
m_callBack(work);
}
AsyncCallback callMe = new AsyncCallback(AddWorkerSocket);
hold.BeginAccept(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 ConnectionCallback(Socket sockMe);
public class Controller
{
private Listener m_listen;
private List<Socketm_wokerList;
//need a connection
//private List<ConnectionconnectList;

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

public void Start()
{
m_listen = new Listener(new
ConnectionCallback(this.AddSocketToList));
m_listen.AcceptNewConnections();
}

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

}

public void Stop()
{
foreach (Socket closeSock in m_wokerList)
{
closeSock.Close();
}
m_listen.StopListening();
}
}
public class Listener
{
private Socket m_listener;
private ConnectionCallback m_callBack;

public Listener(ConnectionCallback callme)
{
m_callBack = callme;
}

public void AcceptNewConnections()
{
this.AcceptNewConnections(2200);
}

public void AcceptNewConnections(int port)
{
IPEndPoint theEnd = new IPEndPoint(IPAddress.Any, port);
m_listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
m_listener.Bind(theEnd);
Console.WriteLine("Binding to " +
theEnd.Address.ToString() + " on port " + theEnd.Port.ToString());
m_listener.Listen(20); //TODO: make this
configurable
Console.WriteLine("Now listening");
AsyncCallback callme = new AsyncCallback(AddWorkerSocket);
m_listener.BeginAccept(callme, m_listener);
}

private void AddWorkerSocket(IAsyncResult ar)
{
Console.WriteLine("Got a Connection");
Socket hold = (Socket)ar.AsyncState;
Socket work = hold.EndAccept(ar);
if (work.Connected)
{
Console.WriteLine("Accepted a connection from " +
work.RemoteEndPoint.ToString());
m_callBack(work);
}
AsyncCallback callMe = new AsyncCallback(AddWorkerSocket);
hold.BeginAccept(callMe, hold);
}

public void StopListening()
{
m_listener.Close();
}
}
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
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"...
0
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 ...
1
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...
1
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...
1
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()...
9
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...
10
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...
4
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...
4
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...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...
0
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...
0
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,...

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.