Advertisement
Guest User

Async Server

a guest
Oct 16th, 2011
636
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.43 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Sockets;
  6. using System.Net;
  7.  
  8. namespace Server
  9. {
  10.     class Program
  11.     {
  12.         /// <summary>
  13.         /// This class holds a TcpClient, its associated Identifier, and a byte buffer for read operations
  14.         /// </summary>
  15.         class IncomingData
  16.         {
  17.             public TcpClient Client { get; protected set; }
  18.             public Guid ClientID { get; protected set; }
  19.             public byte[] buffer { get; protected set; }
  20.  
  21.             public IncomingData(TcpClient client, Guid clientID)
  22.             {
  23.                 this.Client = client;
  24.                 this.ClientID = clientID;
  25.                 buffer = new byte[1024];
  26.             }
  27.         }
  28.  
  29.         /// <summary>
  30.         /// This dictionary holds the data we've received from each client, indexed by the client's unique ID
  31.         /// </summary>
  32.         static IDictionary<Guid, StringBuilder> clientDataCollections = new Dictionary<Guid, StringBuilder>();
  33.  
  34.         static void Main(string[] args)
  35.         {
  36.             Console.WriteLine("Accepting connections. CTRL+C to exit.");
  37.             TcpListener listener = new TcpListener(IPAddress.Any, 7008);
  38.             listener.Start();
  39.             while (true)
  40.             {
  41.                 TcpClient client = listener.AcceptTcpClient();
  42.                
  43.                 // Create a new identifier for this client
  44.                 Guid clientID = Guid.NewGuid();
  45.                
  46.                 clientDataCollections[clientID] = new StringBuilder();
  47.                 Console.WriteLine("Accepted new client {0}", clientID);
  48.                 AcceptData(client, clientID);
  49.             }
  50.         }
  51.  
  52.         /// <summary>
  53.         /// Accepts incoming data for a client in an async manner.
  54.         /// </summary>
  55.         /// <param name="client"></param>
  56.         /// <param name="clientID"></param>
  57.         private static void AcceptData(TcpClient client, Guid clientID)
  58.         {
  59.             // Create a new data object to hold the results of the read, the client we're reading from, and its id
  60.             var dataobj = new IncomingData(client, clientID);
  61.  
  62.             // Begin the async read
  63.             client.GetStream().BeginRead(dataobj.buffer, 0, dataobj.buffer.Length, DataReceivedCallback, dataobj);
  64.         }
  65.  
  66.         /// <summary>
  67.         /// Called when a read operation completes for a given client.
  68.         /// </summary>
  69.         /// <param name="asyncResult"></param>
  70.         private static void DataReceivedCallback(IAsyncResult asyncResult)
  71.         {
  72.             var dataObj = asyncResult.AsyncState as IncomingData;
  73.             if (dataObj == null)
  74.             {
  75.                 Console.WriteLine("Bad state: Couldn't cast async state to IncomingData, or no state found. Press a key.");
  76.                 Console.ReadKey();
  77.                 Environment.Exit(-1);
  78.             }
  79.  
  80.             // We turn the byte data into ASCII text, and then lop off any trailing nulls
  81.             String data = Encoding.ASCII.GetString(dataObj.buffer);
  82.             if (data.IndexOf('\0') != -1)
  83.                 data = data.Substring(0, data.IndexOf('\0'));
  84.  
  85.             bool clientSentEndMessage = false;
  86.             if (data.Length > 0)
  87.             {
  88.                 if (data.Contains("###END###"))
  89.                 {
  90.                     clientSentEndMessage = true;
  91.                     data = data.Replace("###END###", "");
  92.                 }
  93.  
  94.                 // Give some feedback that data arrived
  95.                 Console.WriteLine("Recieved {0} characters of data from client {1}", data.Length, dataObj.ClientID);
  96.  
  97.                 // Add the data to our collector for this client
  98.                 clientDataCollections[dataObj.ClientID].Append(data);
  99.             }
  100.  
  101.             // Clear our async state for this read
  102.             dataObj.Client.GetStream().EndRead(asyncResult);
  103.  
  104.             if (clientSentEndMessage)
  105.             {
  106.                 // That's our "we're done" message
  107.                 Console.WriteLine("Client {0} disconnected", dataObj.ClientID);
  108.                 Console.WriteLine("Final result from {0} is \"{1}\"", dataObj.ClientID, clientDataCollections[dataObj.ClientID].ToString());
  109.             }
  110.             else
  111.             {
  112.                 // Start a new read operation for this client
  113.                 AcceptData(dataObj.Client, dataObj.ClientID);
  114.             }  
  115.         }
  116.     }
  117. }
  118.  
  119.  
  120.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement