Re: What is the best way to stop a Socket.BeginAccept call?

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



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

<darthghandi@xxxxxxxxx> wrote in message
news:1172803491.973823.56370@xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
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...@xxxxxxxxx> wrote in message

news:1172692695.291082.106910@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

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<Socket> m_wokerList;
//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
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();
}
}


.



Relevant Pages

  • Re: max connections
    ... Or you mean that peer succeed to to connectwith 17th socket just ... I have an application running a TCP/IP server programmed in C ... closing the listensocket when the connections reached 16. ... The listener starts and 16 threads are started with each an acceptcall ...
    (microsoft.public.win32.programmer.networks)
  • Re: Multiple listen() on a socket
    ... What I want to do is to change backlog of the in-use listener ... > socket. ... allow 3 connections) and then goes to sleep, ...
    (comp.unix.programmer)
  • can you use delegates to pass a copy of an object when an event happens?
    ... I am creating a listener class that listens for incoming connections. ... happen and pass that connected socket to a different thread for the ... public void AcceptNewConnections() ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: max connections
    ... When you'll send data in such situation server which closed that socket on ... The time in between the last accept en close listener is ... server is now limited by 16 connections simultaneously. ...
    (microsoft.public.win32.programmer.networks)
  • Asynchronous Socket Server data
    ... The socket server knows what type of data it expects due to the interface ... I can have 1 databuffer only for each datatype to handle multiple connections? ... int bytesRead = handler.EndReceive; ... packetIndex, bytesRead); ...
    (microsoft.public.dotnet.languages.csharp)