Identifying client that sent data to Asynchronous socket.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Macca

    #1

    Identifying client that sent data to Asynchronous socket.

    My app has an asynchronous socket server. It will have 20 clients connected
    to the server. Each client sends data every 500 millisecondsThe Connections
    once established will not be closed unless there is a problem with the
    connection.

    I need to know which client has sent the incoming data as each client has
    its own buffer on my "server" app.

    I am using the standard asynch socket code from MSDN to listen for
    connections and they process their data as shown below.

    My question is :- As my connections are permanent once established is there
    a way in the read callback function to identify from which client the data
    has come from?

    using System;
    using System.Net;
    using System.Net.Sock ets;
    using System.Text;
    using System.Threadin g;

    // State object for reading client data asynchronously
    public class StateObject {
    // Client socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 1024;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder sb = new StringBuilder() ;
    }

    public class AsynchronousSoc ketListener {
    // Thread signal.
    public static ManualResetEven t allDone = new ManualResetEven t(false);

    public AsynchronousSoc ketListener() {
    }

    public static void StartListening( ) {
    // Data buffer for incoming data.
    byte[] bytes = new Byte[1024];

    // Establish the local endpoint for the socket.
    // The DNS name of the computer
    // running the listener is "host.contoso.c om".
    IPHostEntry ipHostInfo = Dns.Resolve(Dns .GetHostName()) ;
    IPAddress ipAddress = ipHostInfo.Addr essList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAd dress, 11000);

    // Create a TCP/IP socket.
    Socket listener = new Socket(AddressF amily.InterNetw ork,
    SocketType.Stre am, ProtocolType.Tc p );

    // Bind the socket to the local endpoint and listen for incoming
    connections.
    try {
    listener.Bind(l ocalEndPoint);
    listener.Listen (100);

    while (true) {
    // Set the event to nonsignaled state.
    allDone.Reset() ;

    // Start an asynchronous socket to listen for connections.
    Console.WriteLi ne("Waiting for a connection...") ;
    listener.BeginA ccept(
    new AsyncCallback(A cceptCallback),
    listener );

    // Wait until a connection is made before continuing.
    allDone.WaitOne ();
    }

    } catch (Exception e) {
    Console.WriteLi ne(e.ToString() );
    }

    Console.WriteLi ne("\nPress ENTER to continue...");
    Console.Read();

    }

    public static void AcceptCallback( IAsyncResult ar) {
    // Signal the main thread to continue.
    allDone.Set();

    // Get the socket that handles the client request.
    Socket listener = (Socket) ar.AsyncState;
    Socket handler = listener.EndAcc ept(ar);

    // Create the state object.
    StateObject state = new StateObject();
    state.workSocke t = handler;
    handler.BeginRe ceive( state.buffer, 0, StateObject.Buf ferSize, 0,
    new AsyncCallback(R eadCallback), state);
    }

    public static void ReadCallback(IA syncResult ar) {
    String content = String.Empty;

    // Retrieve the state object and the handler socket
    // from the asynchronous state object.
    StateObject state = (StateObject) ar.AsyncState;
    Socket handler = state.workSocke t;

    // Read data from the client socket.
    int bytesRead = handler.EndRece ive(ar);

    if (bytesRead > 0) {
    // There might be more data, so store the data received so far.
    state.sb.Append (Encoding.ASCII .GetString(
    state.buffer,0, bytesRead));

    // Check for end-of-file tag. If it is not there, read
    // more data.
    content = state.sb.ToStri ng();
    if (content.IndexO f("<EOF>") > -1) {
    // All the data has been read from the
    // client. Display it on the console.
    Console.WriteLi ne("Read {0} bytes from socket. \n Data : {1}",
    content.Length, content );
    // Echo the data back to the client.
    Send(handler, content);
    } else {
    // Not all data received. Get more.
    handler.BeginRe ceive(state.buf fer, 0,
    StateObject.Buf ferSize, 0,
    new AsyncCallback(R eadCallback), state);
    }
    }
    }

    private static void Send(Socket handler, String data) {
    // Convert the string data to byte data using ASCII encoding.
    byte[] byteData = Encoding.ASCII. GetBytes(data);

    // Begin sending the data to the remote device.
    handler.BeginSe nd(byteData, 0, byteData.Length , 0,
    new AsyncCallback(S endCallback), handler);
    }

    private static void SendCallback(IA syncResult ar) {
    try {
    // Retrieve the socket from the state object.
    Socket handler = (Socket) ar.AsyncState;

    // Complete sending the data to the remote device.
    int bytesSent = handler.EndSend (ar);
    Console.WriteLi ne("Sent {0} bytes to client.", bytesSent);

    handler.Shutdow n(SocketShutdow n.Both);
    handler.Close() ;

    } catch (Exception e) {
    Console.WriteLi ne(e.ToString() );
    }
    }


    public static int Main(String[] args) {
    StartListening( );
    return 0;
    }
    }


    Thanks In Advance,
    Macca
  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: Identifying client that sent data to Asynchronous socket.

    Macca,

    You should be able to get the IP address of the client from the socket
    that you are listening on. Beyond that, any information about the client
    that you are looking for will have to be sent by the client to you.

    Hope this helps.


    --
    - Nicholas Paldino [.NET/C# MVP]
    - mvp@spam.guard. caspershouse.co m

    "Macca" <Macca@discussi ons.microsoft.c om> wrote in message
    news:AB591842-2FB0-4133-A065-A670DA01A404@mi crosoft.com...[color=blue]
    > My app has an asynchronous socket server. It will have 20 clients
    > connected
    > to the server. Each client sends data every 500 millisecondsThe
    > Connections
    > once established will not be closed unless there is a problem with the
    > connection.
    >
    > I need to know which client has sent the incoming data as each client has
    > its own buffer on my "server" app.
    >
    > I am using the standard asynch socket code from MSDN to listen for
    > connections and they process their data as shown below.
    >
    > My question is :- As my connections are permanent once established is
    > there
    > a way in the read callback function to identify from which client the data
    > has come from?
    >
    > using System;
    > using System.Net;
    > using System.Net.Sock ets;
    > using System.Text;
    > using System.Threadin g;
    >
    > // State object for reading client data asynchronously
    > public class StateObject {
    > // Client socket.
    > public Socket workSocket = null;
    > // Size of receive buffer.
    > public const int BufferSize = 1024;
    > // Receive buffer.
    > public byte[] buffer = new byte[BufferSize];
    > // Received data string.
    > public StringBuilder sb = new StringBuilder() ;
    > }
    >
    > public class AsynchronousSoc ketListener {
    > // Thread signal.
    > public static ManualResetEven t allDone = new ManualResetEven t(false);
    >
    > public AsynchronousSoc ketListener() {
    > }
    >
    > public static void StartListening( ) {
    > // Data buffer for incoming data.
    > byte[] bytes = new Byte[1024];
    >
    > // Establish the local endpoint for the socket.
    > // The DNS name of the computer
    > // running the listener is "host.contoso.c om".
    > IPHostEntry ipHostInfo = Dns.Resolve(Dns .GetHostName()) ;
    > IPAddress ipAddress = ipHostInfo.Addr essList[0];
    > IPEndPoint localEndPoint = new IPEndPoint(ipAd dress, 11000);
    >
    > // Create a TCP/IP socket.
    > Socket listener = new Socket(AddressF amily.InterNetw ork,
    > SocketType.Stre am, ProtocolType.Tc p );
    >
    > // Bind the socket to the local endpoint and listen for incoming
    > connections.
    > try {
    > listener.Bind(l ocalEndPoint);
    > listener.Listen (100);
    >
    > while (true) {
    > // Set the event to nonsignaled state.
    > allDone.Reset() ;
    >
    > // Start an asynchronous socket to listen for connections.
    > Console.WriteLi ne("Waiting for a connection...") ;
    > listener.BeginA ccept(
    > new AsyncCallback(A cceptCallback),
    > listener );
    >
    > // Wait until a connection is made before continuing.
    > allDone.WaitOne ();
    > }
    >
    > } catch (Exception e) {
    > Console.WriteLi ne(e.ToString() );
    > }
    >
    > Console.WriteLi ne("\nPress ENTER to continue...");
    > Console.Read();
    >
    > }
    >
    > public static void AcceptCallback( IAsyncResult ar) {
    > // Signal the main thread to continue.
    > allDone.Set();
    >
    > // Get the socket that handles the client request.
    > Socket listener = (Socket) ar.AsyncState;
    > Socket handler = listener.EndAcc ept(ar);
    >
    > // Create the state object.
    > StateObject state = new StateObject();
    > state.workSocke t = handler;
    > handler.BeginRe ceive( state.buffer, 0, StateObject.Buf ferSize, 0,
    > new AsyncCallback(R eadCallback), state);
    > }
    >
    > public static void ReadCallback(IA syncResult ar) {
    > String content = String.Empty;
    >
    > // Retrieve the state object and the handler socket
    > // from the asynchronous state object.
    > StateObject state = (StateObject) ar.AsyncState;
    > Socket handler = state.workSocke t;
    >
    > // Read data from the client socket.
    > int bytesRead = handler.EndRece ive(ar);
    >
    > if (bytesRead > 0) {
    > // There might be more data, so store the data received so
    > far.
    > state.sb.Append (Encoding.ASCII .GetString(
    > state.buffer,0, bytesRead));
    >
    > // Check for end-of-file tag. If it is not there, read
    > // more data.
    > content = state.sb.ToStri ng();
    > if (content.IndexO f("<EOF>") > -1) {
    > // All the data has been read from the
    > // client. Display it on the console.
    > Console.WriteLi ne("Read {0} bytes from socket. \n Data :
    > {1}",
    > content.Length, content );
    > // Echo the data back to the client.
    > Send(handler, content);
    > } else {
    > // Not all data received. Get more.
    > handler.BeginRe ceive(state.buf fer, 0,
    > StateObject.Buf ferSize, 0,
    > new AsyncCallback(R eadCallback), state);
    > }
    > }
    > }
    >
    > private static void Send(Socket handler, String data) {
    > // Convert the string data to byte data using ASCII encoding.
    > byte[] byteData = Encoding.ASCII. GetBytes(data);
    >
    > // Begin sending the data to the remote device.
    > handler.BeginSe nd(byteData, 0, byteData.Length , 0,
    > new AsyncCallback(S endCallback), handler);
    > }
    >
    > private static void SendCallback(IA syncResult ar) {
    > try {
    > // Retrieve the socket from the state object.
    > Socket handler = (Socket) ar.AsyncState;
    >
    > // Complete sending the data to the remote device.
    > int bytesSent = handler.EndSend (ar);
    > Console.WriteLi ne("Sent {0} bytes to client.", bytesSent);
    >
    > handler.Shutdow n(SocketShutdow n.Both);
    > handler.Close() ;
    >
    > } catch (Exception e) {
    > Console.WriteLi ne(e.ToString() );
    > }
    > }
    >
    >
    > public static int Main(String[] args) {
    > StartListening( );
    > return 0;
    > }
    > }
    >
    >
    > Thanks In Advance,
    > Macca[/color]


    Comment

    • John Murray

      #3
      Re: Identifying client that sent data to Asynchronous socket.

      After the line

      Socket handler = listener.EndAcc ept(ar);

      You should be able to call

      handler.RemoteE ndPoint

      to get information on the source of the connection


      Macca wrote:[color=blue]
      > My app has an asynchronous socket server. It will have 20 clients connected
      > to the server. Each client sends data every 500 millisecondsThe Connections
      > once established will not be closed unless there is a problem with the
      > connection.
      >
      > I need to know which client has sent the incoming data as each client has
      > its own buffer on my "server" app.
      >
      > I am using the standard asynch socket code from MSDN to listen for
      > connections and they process their data as shown below.
      >
      > My question is :- As my connections are permanent once established is there
      > a way in the read callback function to identify from which client the data
      > has come from?
      >
      > using System;
      > using System.Net;
      > using System.Net.Sock ets;
      > using System.Text;
      > using System.Threadin g;
      >
      > // State object for reading client data asynchronously
      > public class StateObject {
      > // Client socket.
      > public Socket workSocket = null;
      > // Size of receive buffer.
      > public const int BufferSize = 1024;
      > // Receive buffer.
      > public byte[] buffer = new byte[BufferSize];
      > // Received data string.
      > public StringBuilder sb = new StringBuilder() ;
      > }
      >
      > public class AsynchronousSoc ketListener {
      > // Thread signal.
      > public static ManualResetEven t allDone = new ManualResetEven t(false);
      >
      > public AsynchronousSoc ketListener() {
      > }
      >
      > public static void StartListening( ) {
      > // Data buffer for incoming data.
      > byte[] bytes = new Byte[1024];
      >
      > // Establish the local endpoint for the socket.
      > // The DNS name of the computer
      > // running the listener is "host.contoso.c om".
      > IPHostEntry ipHostInfo = Dns.Resolve(Dns .GetHostName()) ;
      > IPAddress ipAddress = ipHostInfo.Addr essList[0];
      > IPEndPoint localEndPoint = new IPEndPoint(ipAd dress, 11000);
      >
      > // Create a TCP/IP socket.
      > Socket listener = new Socket(AddressF amily.InterNetw ork,
      > SocketType.Stre am, ProtocolType.Tc p );
      >
      > // Bind the socket to the local endpoint and listen for incoming
      > connections.
      > try {
      > listener.Bind(l ocalEndPoint);
      > listener.Listen (100);
      >
      > while (true) {
      > // Set the event to nonsignaled state.
      > allDone.Reset() ;
      >
      > // Start an asynchronous socket to listen for connections.
      > Console.WriteLi ne("Waiting for a connection...") ;
      > listener.BeginA ccept(
      > new AsyncCallback(A cceptCallback),
      > listener );
      >
      > // Wait until a connection is made before continuing.
      > allDone.WaitOne ();
      > }
      >
      > } catch (Exception e) {
      > Console.WriteLi ne(e.ToString() );
      > }
      >
      > Console.WriteLi ne("\nPress ENTER to continue...");
      > Console.Read();
      >
      > }
      >
      > public static void AcceptCallback( IAsyncResult ar) {
      > // Signal the main thread to continue.
      > allDone.Set();
      >
      > // Get the socket that handles the client request.
      > Socket listener = (Socket) ar.AsyncState;
      > Socket handler = listener.EndAcc ept(ar);
      >
      > // Create the state object.
      > StateObject state = new StateObject();
      > state.workSocke t = handler;
      > handler.BeginRe ceive( state.buffer, 0, StateObject.Buf ferSize, 0,
      > new AsyncCallback(R eadCallback), state);
      > }
      >
      > public static void ReadCallback(IA syncResult ar) {
      > String content = String.Empty;
      >
      > // Retrieve the state object and the handler socket
      > // from the asynchronous state object.
      > StateObject state = (StateObject) ar.AsyncState;
      > Socket handler = state.workSocke t;
      >
      > // Read data from the client socket.
      > int bytesRead = handler.EndRece ive(ar);
      >
      > if (bytesRead > 0) {
      > // There might be more data, so store the data received so far.
      > state.sb.Append (Encoding.ASCII .GetString(
      > state.buffer,0, bytesRead));
      >
      > // Check for end-of-file tag. If it is not there, read
      > // more data.
      > content = state.sb.ToStri ng();
      > if (content.IndexO f("<EOF>") > -1) {
      > // All the data has been read from the
      > // client. Display it on the console.
      > Console.WriteLi ne("Read {0} bytes from socket. \n Data : {1}",
      > content.Length, content );
      > // Echo the data back to the client.
      > Send(handler, content);
      > } else {
      > // Not all data received. Get more.
      > handler.BeginRe ceive(state.buf fer, 0,
      > StateObject.Buf ferSize, 0,
      > new AsyncCallback(R eadCallback), state);
      > }
      > }
      > }
      >
      > private static void Send(Socket handler, String data) {
      > // Convert the string data to byte data using ASCII encoding.
      > byte[] byteData = Encoding.ASCII. GetBytes(data);
      >
      > // Begin sending the data to the remote device.
      > handler.BeginSe nd(byteData, 0, byteData.Length , 0,
      > new AsyncCallback(S endCallback), handler);
      > }
      >
      > private static void SendCallback(IA syncResult ar) {
      > try {
      > // Retrieve the socket from the state object.
      > Socket handler = (Socket) ar.AsyncState;
      >
      > // Complete sending the data to the remote device.
      > int bytesSent = handler.EndSend (ar);
      > Console.WriteLi ne("Sent {0} bytes to client.", bytesSent);
      >
      > handler.Shutdow n(SocketShutdow n.Both);
      > handler.Close() ;
      >
      > } catch (Exception e) {
      > Console.WriteLi ne(e.ToString() );
      > }
      > }
      >
      >
      > public static int Main(String[] args) {
      > StartListening( );
      > return 0;
      > }
      > }
      >
      >
      > Thanks In Advance,
      > Macca[/color]

      Comment

      Working...