Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net.Sockets;
- using System.Net;
- namespace Server
- {
- class Program
- {
- /// <summary>
- /// This class holds a TcpClient, its associated Identifier, and a byte buffer for read operations
- /// </summary>
- class IncomingData
- {
- public TcpClient Client { get; protected set; }
- public Guid ClientID { get; protected set; }
- public byte[] buffer { get; protected set; }
- public IncomingData(TcpClient client, Guid clientID)
- {
- this.Client = client;
- this.ClientID = clientID;
- buffer = new byte[1024];
- }
- }
- /// <summary>
- /// This dictionary holds the data we've received from each client, indexed by the client's unique ID
- /// </summary>
- static IDictionary<Guid, StringBuilder> clientDataCollections = new Dictionary<Guid, StringBuilder>();
- static void Main(string[] args)
- {
- Console.WriteLine("Accepting connections. CTRL+C to exit.");
- TcpListener listener = new TcpListener(IPAddress.Any, 7008);
- listener.Start();
- while (true)
- {
- TcpClient client = listener.AcceptTcpClient();
- // Create a new identifier for this client
- Guid clientID = Guid.NewGuid();
- clientDataCollections[clientID] = new StringBuilder();
- Console.WriteLine("Accepted new client {0}", clientID);
- AcceptData(client, clientID);
- }
- }
- /// <summary>
- /// Accepts incoming data for a client in an async manner.
- /// </summary>
- /// <param name="client"></param>
- /// <param name="clientID"></param>
- private static void AcceptData(TcpClient client, Guid clientID)
- {
- // Create a new data object to hold the results of the read, the client we're reading from, and its id
- var dataobj = new IncomingData(client, clientID);
- // Begin the async read
- client.GetStream().BeginRead(dataobj.buffer, 0, dataobj.buffer.Length, DataReceivedCallback, dataobj);
- }
- /// <summary>
- /// Called when a read operation completes for a given client.
- /// </summary>
- /// <param name="asyncResult"></param>
- private static void DataReceivedCallback(IAsyncResult asyncResult)
- {
- var dataObj = asyncResult.AsyncState as IncomingData;
- if (dataObj == null)
- {
- Console.WriteLine("Bad state: Couldn't cast async state to IncomingData, or no state found. Press a key.");
- Console.ReadKey();
- Environment.Exit(-1);
- }
- // We turn the byte data into ASCII text, and then lop off any trailing nulls
- String data = Encoding.ASCII.GetString(dataObj.buffer);
- if (data.IndexOf('\0') != -1)
- data = data.Substring(0, data.IndexOf('\0'));
- bool clientSentEndMessage = false;
- if (data.Length > 0)
- {
- if (data.Contains("###END###"))
- {
- clientSentEndMessage = true;
- data = data.Replace("###END###", "");
- }
- // Give some feedback that data arrived
- Console.WriteLine("Recieved {0} characters of data from client {1}", data.Length, dataObj.ClientID);
- // Add the data to our collector for this client
- clientDataCollections[dataObj.ClientID].Append(data);
- }
- // Clear our async state for this read
- dataObj.Client.GetStream().EndRead(asyncResult);
- if (clientSentEndMessage)
- {
- // That's our "we're done" message
- Console.WriteLine("Client {0} disconnected", dataObj.ClientID);
- Console.WriteLine("Final result from {0} is \"{1}\"", dataObj.ClientID, clientDataCollections[dataObj.ClientID].ToString());
- }
- else
- {
- // Start a new read operation for this client
- AcceptData(dataObj.Client, dataObj.ClientID);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement