title: TCP Socket Server custom class for socket identifier in C#
body: <p>I've been looking at many tcp client/server examples and would want to know how one can go about creating a method to identify each client. One way I know is through lets say, a log in authentication. I know how to connect, and query a database, but how would I lets say after successful authentication, take the username and say this username is this socket. A class example or simple method would be appreciated as an example. I want to be able to target all connected clients by their username from a database individually.</p>
  
  <p>Example I'm using for server</p>
  
  <pre><code> using System;
  
      using System.Collections.Generic;
  
      using System.Net;
  
      using System.Net.Sockets;
  
      using System.Text;
  
  
  
      namespace MultiServer
  
      {
  
          class Program
  
          {
  
              private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  
              private static readonly List&lt;Socket&gt; clientSockets = new List&lt;Socket&gt;();
  
              private const int BUFFER_SIZE = 2048;
  
              private const int PORT = 100;
  
              private static readonly byte[] buffer = new byte[BUFFER_SIZE];
  
  
  
              static void Main()
  
              {
  
                  Console.Title = "Server";
  
                  SetupServer();
  
                  Console.ReadLine(); // When we press enter close everything
  
                  CloseAllSockets();
  
              }
  
  
  
              private static void SetupServer()
  
              {
  
                  Console.WriteLine("Setting up server...");
  
                  serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT));
  
                  serverSocket.Listen(0);
  
                  serverSocket.BeginAccept(AcceptCallback, null);
  
                  Console.WriteLine("Server setup complete");
  
              }
  
  
  
              /// &lt;summary&gt;
  
              /// Close all connected client (we do not need to shutdown the server socket as its connections
  
              /// are already closed with the clients).
  
              /// &lt;/summary&gt;
  
              private static void CloseAllSockets()
  
              {
  
                  foreach (Socket socket in clientSockets)
  
                  {
  
                      socket.Shutdown(SocketShutdown.Both);
  
                      socket.Close();
  
                  }
  
  
  
                  serverSocket.Close();
  
              }
  
  
  
              private static void AcceptCallback(IAsyncResult AR)
  
              {
  
                  Socket socket;
  
  
  
                  try
  
                  {
  
                      socket = serverSocket.EndAccept(AR);
  
                  }
  
                  catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)
  
                  {
  
                      return;
  
                  }
  
  
  
                 clientSockets.Add(socket);
  
                 socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
  
                 Console.WriteLine("Client connected, waiting for request...");
  
                 serverSocket.BeginAccept(AcceptCallback, null);
  
              }
  
  
  
              private static void ReceiveCallback(IAsyncResult AR)
  
              {
  
                  Socket current = (Socket)AR.AsyncState;
  
                  int received;
  
  
  
                  try
  
                  {
  
                      received = current.EndReceive(AR);
  
                  }
  
                  catch (SocketException)
  
                  {
  
                      Console.WriteLine("Client forcefully disconnected");
  
                      // Don't shutdown because the socket may be disposed and its disconnected anyway.
  
                      current.Close(); 
  
                      clientSockets.Remove(current);
  
                      return;
  
                  }
  
  
  
                  byte[] recBuf = new byte[received];
  
                  Array.Copy(buffer, recBuf, received);
  
                  string text = Encoding.ASCII.GetString(recBuf);
  
                  Console.WriteLine("Received Text: " + text);
  
  
  
                  if (text.ToLower() == "get time") // Client requested time
  
                  {
  
                      Console.WriteLine("Text is a get time request");
  
                      byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
  
                      current.Send(data);
  
                      Console.WriteLine("Time sent to client");
  
                  }
  
                  else if (text.ToLower() == "exit") // Client wants to exit gracefully
  
                  {
  
                      // Always Shutdown before closing
  
                      current.Shutdown(SocketShutdown.Both);
  
                      current.Close();
  
                      clientSockets.Remove(current);
  
                      Console.WriteLine("Client disconnected");
  
                      return;
  
                  }
  
                  else
  
                  {
  
                      Console.WriteLine("Text is an invalid request");
  
                      byte[] data = Encoding.ASCII.GetBytes("Invalid request");
  
                      current.Send(data);
  
                      Console.WriteLine("Warning Sent");
  
                  }
  
  
  
                  current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
  
              }
  
          }
  
      }
  </code></pre>