Using asynchronous sockets in C#

How to have a listener for a socket in C#:

  • Use System.Net.Sockets
  • TcpListener listener=new TcpListener(System.Net.IPAddress.Parse("0.0.0.0"),2000);
  • Create the following callback:
protected void DoAcceptCallback(IAsyncResult ar){
    TcpListener tl = (TcpListener)ar.AsyncState;
    Socket s = tl.EndAcceptSocket(ar);
 
    //Log the traffic
    DataRow dr=traffic.NewRow();
    dr["ID"] = 0;
    dr["RemoteIP"] = s.RemoteEndPoint.ToString();
    traffic.Rows.Add(dr);
 
    s.Close();
}
 
No votes yet