Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press

Buy directly from Paradoxal Press at $33.99 (Save 43%)



Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA


Listing 17-21 extracted from chapter Input/Output and streams


Listing 17-20<     > Listing 17-22


This listing can be compiled with the command line:
csc.exe /out:Server.exe /target:exe Example_17_21_to_rename_Server.cs
Errors: 0 Warnings: 0


Example_17_21_to_rename_Server.cs
using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Security.Principal;
using System.Threading;

class ProgServeur {
   static readonly ushort port = 50000;

   static void Main() {
      IPAddress ipAddress = new IPAddress(new byte[] { 12700});
      TcpListener tcpL = new TcpListener(ipAddress, port);
      tcpL.Start();
      while (true) {
         try {
            Console.WriteLine("Waiting for client...");
            TcpClient tcpClient = tcpL.AcceptTcpClient();
            Console.WriteLine("Client connected.");
            ProcessClientRequest(tcpClient.GetStream());
            Console.WriteLine("Client disconnected.");
         catch (Exception e) {
            Console.WriteLine(e.Message);
         }
      }
   }
   static void ProcessClientRequest(NetworkStream networkStream) {
      NegotiateStream streamAuth = new NegotiateStream(networkStream);
      streamAuth.AuthenticateAsServer(
         CredentialCache.DefaultNetworkCredentials,
         ProtectionLevel.EncryptAndSign,
         TokenImpersonationLevel.Impersonation);
      WindowsPrincipal principal = new WindowsPrincipal(
         streamAuth.RemoteIdentity as WindowsIdentity );
      // Don't process the request if the authentificated 
      // Windows client is not an administrator.
      if( !principal.IsInRole( @"BUILTIN\Administrators" ) ){
         networkStream.Close();
         return;
      }

      StreamWriter streamWriter = new StreamWriter( streamAuth );
      StreamReader streamReader = new StreamReader@"C:/Text/File.txt" );
      string sTmp = streamReader.ReadLine();
      try {
         while ( sTmp != null ) {
            Console.WriteLine( "Sending: {0}", sTmp );
            streamWriter.WriteLine( sTmp );
            streamWriter.Flush();
            sTmp = streamReader.ReadLine();
         }
      } finally {
         streamReader.Close();
         streamWriter.Close();
         streamAuth.Close();
         networkStream.Close();
      }
   }
}	
Copyright Patrick Smacchia 2006 2007