AsyncSocket doesn't accept another connection

  • Thread starter Thread starter Dan Holmes
  • Start date Start date
D

Dan Holmes

The first tim ethis app is run it works just fine as well as every
restart. What i can't figure is how to get it to accept a connection
after the first one.

This is a console app but i don't think that matters.


using SNS = System.Net.Sockets;


......

SNS.TcpListener listn = new SNS.TcpListener(System.Net.IPAddress.Any,
20000);
listn.Start();

IAsyncResult ar = listn.BeginAcceptTcpClient(new
AsyncCallback(ProcessSocket), listn);


.....

static void ProcessSocket(IAsyncResult ar)
{
// Get the listener that handles the client request.
SNS.TcpListener listener = (SNS.TcpListener)ar.AsyncState;
SNS.TcpClient clientSocket = listener.EndAcceptTcpClient(ar);

Console.WriteLine("Client connected completed");

UpdateAndRestart();

clientSocket.Close();

listener.Stop();
listener.Start();
}
 
After the EndAcceptSocket in ProcessSocket, you need to tell your server
socket to listen for another connection.

Mike.
 
Hi

You need to do it multithread:

main thread:
loop
listen connection
got connection, spawn a new thread to handle it
end loop

This is actual code ( you may need to have the listening method a worker
thread too):
private void ListenForConnections()
{

TcpListener lis = new TcpListener( 4455);

Socket source = lis.AcceptSocket();
Conn conn = new Conn();
conn.Source = source;
q.Enqueue( conn);
new System.Threading.Thread( new System.Threading.ThreadStart(
ConnHandler)).Start();

}
void ConnHandler()
{
}
 
I wouldn't take the mulit-threaded route shown here. There are much, much
better ways do to it.

Change your Process Socket method to:

static void ProcessSocket(IAsyncResult ar)
{
// Get the listener that handles the client request.
SNS.TcpListener listener = (SNS.TcpListener)ar.AsyncState;
SNS.TcpClient clientSocket = listener.EndAcceptTcpClient(ar);

//*** New line here: Put the original socket back in async
listen mode
listener.BeginAcceptTcpClient(new AsyncCallback(ProcessSocket),
listn);

//*** Most people would then put the new socket into Async Read
mode
clientSocket.BeginRead(new AsyncCallback(IncomingData),
clientSocket);
}

This approach, using Async Sockets, will give you excellent performacne,
nearly unlimited scalability, and is easier to use than trying to manage
your own threads.
 
Back
Top