Veikedo

pony

Nov 9th, 2013
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1.   public class Server
  2.   {
  3.     public async void Run(int port)
  4.     {
  5.       TcpListener server = null;
  6.  
  7.       try
  8.       {
  9.         IPAddress localAddr = IPAddress.Parse("127.0.0.1");
  10.         server = new TcpListener(localAddr, port);
  11.  
  12.         // Start listening for client requests.
  13.         server.Start();
  14.  
  15.         // Buffer for reading data
  16.         var bytes = new Byte[256];
  17.  
  18.         // Enter the listening loop.
  19.         while (true)
  20.         {
  21.           RaiseLog("Waiting for a connection... ");
  22.  
  23.           // Perform a blocking call to accept requests.
  24.           // You could also user server.AcceptSocket() here.
  25.           TcpClient client = await server.AcceptTcpClientAsync();
  26.           RaiseLog("Connected!");
  27.  
  28.           // Get a stream object for reading and writing
  29.           NetworkStream stream = client.GetStream();
  30.  
  31.           int i;
  32.  
  33.           // Loop to receive all the data sent by the client.
  34.           while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
  35.           {
  36.             // Translate data bytes to a UTF8 string.
  37.             string data = Encoding.UTF8.GetString(bytes, 0, i);
  38.             RaiseLog("Received: {0}", data);
  39.  
  40.             // Process the data sent by the client.
  41.             data = data.ToUpper();
  42.  
  43.             byte[] msg = Encoding.UTF8.GetBytes(data);
  44.  
  45.             // Send back a response.
  46.             stream.Write(msg, 0, msg.Length);
  47.             RaiseLog("Sent: {0}", data);
  48.           }
  49.  
  50.           // Shutdown and end connection
  51.           client.Close();
  52.         }
  53.       }
  54.       catch (SocketException e)
  55.       {
  56.         RaiseLog("SocketException: {0}", e);
  57.       }
  58.       finally
  59.       {
  60.         // Stop listening for new clients.
  61.         if (server != null)
  62.         {
  63.           server.Stop();
  64.         }
  65.       }
  66.     }
  67.  
  68.     private void RaiseLog(string format, params object[] args)
  69.     {
  70.       var tmp = Log;
  71.       if (tmp != null)
  72.       {
  73.         string s = string.Format(format, args);
  74.         tmp(this, s);
  75.       }
  76.     }
  77.  
  78.     public event EventHandler<string> Log;
  79.   }
  80.  
  81.     private static void Main()
  82.     {
  83.       var server = new Server();
  84.       server.Log += (s, e) => Console.WriteLine(e);
  85.  
  86.       server.Run(port: 145);
  87. ...
  88.    }
Advertisement
Add Comment
Please, Sign In to add comment