We have an application in production that is supposed to be a multithreaded socket listener. I am starting to have my doubts because the logs the app generates makes it appear as if it is processing the streams it receives synchronously. In an effort of trying not to paste a wall of code here, I will supply the first portion of supposedly asynch tcp code: Is this proper practice?
/// <summary>
/// Start an Asynchronous Socket to listen for connections.
/// </summary>
public static void StartListening()
{
Socket listenerSocket = null;
try
{
var ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
var ipAddress = ipHostInfo.AddressList[Socket.OSSupportsIPv6 ? 1 : 0];
//Create TCP/IP Socket
listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listenerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
listenerSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
//Bind the socket to the local endpoint and listen for incoming connections.
//listenerSocket.Bind(new IPEndPoint(ipAddress, m_client.RemotePort));
listenerSocket.Bind(new IPEndPoint(ipAddress, Int32.Parse(ConfigurationManager.AppSettings["ListenerPort"])));
listenerSocket.Listen(m_maxSocketConnections);
while (true)
{
//Set the event to nonsignaled state
m_pAllDone.Reset();
//Start an asynchronous socket
listenerSocket.BeginAccept(new AsyncCallback(AcceptCallback), listenerSocket);
//Wait until a connection is made and processed before continuing
m_pAllDone.WaitOne();
}
}
This call is not multithreaded, it is simply asynchronous. From the docs:
When your application calls BeginAccept, the system usually uses a separate thread to execute the specified callback method and blocks on EndAccept until a pending connection is retrieved.The BeginAccept method creates one other thread that blocks and processes the incoming packets asynchronously. It does not spawn a NEW thread every time a message comes in.