Better Data Sender

image_pdfimage_print
   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

public class BetterDataSender
{
   private void SendData(NetworkStream strm, SerialEmployee emp)
   {
      IFormatter formatter = new SoapFormatter();
      MemoryStream memstrm = new MemoryStream();

      formatter.Serialize(memstrm, emp);
      byte[] data = memstrm.GetBuffer();
      int memsize = (int)memstrm.Length;
      byte[] size = BitConverter.GetBytes(memsize);
      strm.Write(size, 0, 4);
      strm.Write(data, 0, memsize);
      strm.Flush();
      memstrm.Close();
   }

   public BetterDataSender()
   {
      SerialEmployee emp1 = new SerialEmployee();
      SerialEmployee emp2 = new SerialEmployee();

      emp1.EmployeeID = 1;
      emp1.LastName = "Blum";
      emp1.FirstName = "Katie Jane";
      emp1.YearsService = 12;
      emp1.Salary = 35000.50;

      emp2.EmployeeID = 2;
      emp2.LastName = "Blum";
      emp2.FirstName = "Jessica";
      emp2.YearsService = 9;
      emp2.Salary = 23700.30;

      TcpClient client = new TcpClient("127.0.0.1", 9050);
      NetworkStream strm = client.GetStream();

      SendData(strm, emp1);
      SendData(strm, emp2);
      strm.Close();
      client.Close();
   }

   public static void Main()
   {
      BetterDataSender bds = new BetterDataSender();
   }
}


[Serializable]
public class SerialEmployee
{
   public int EmployeeID;
   public string LastName;
   public string FirstName;
   public int YearsService;
   public double Salary;

   public SerialEmployee()
   {
      EmployeeID = 0;
      LastName = null;
      FirstName = null;
      YearsService = 0;
      Salary = 0.0;
   }
}

           
          


Better Data Receiver

image_pdfimage_print
   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

public class BetterDataRcvr
{
   private SerialEmployee RecvData(NetworkStream strm)
   {
      MemoryStream memstrm = new MemoryStream();
      byte[] data = new byte[4];
      int recv = strm.Read(data, 0, 4);
      int size = BitConverter.ToInt32(data, 0);
      int offset = 0;
      while(size > 0)
      {
         data = new byte[1024];
         recv = strm.Read(data, 0, size);
         memstrm.Write(data, offset, recv);
         offset += recv;
         size -= recv;
      }
      IFormatter formatter = new SoapFormatter();
      memstrm.Position = 0;
      SerialEmployee emp = (SerialEmployee)formatter.Deserialize(memstrm);
      memstrm.Close();
      return emp;
   }      

   public BetterDataRcvr()
   {
      TcpListener server = new TcpListener(9050);
      server.Start();
      TcpClient client = server.AcceptTcpClient();
      NetworkStream strm = client.GetStream();

      SerialEmployee emp1 = RecvData(strm);
      Console.WriteLine("emp1.EmployeeID = {0}", emp1.EmployeeID);
      Console.WriteLine("emp1.LastName = {0}", emp1.LastName);
      Console.WriteLine("emp1.FirstName = {0}", emp1.FirstName);
      Console.WriteLine("emp1.YearsService = {0}", emp1.YearsService);
      Console.WriteLine("emp1.Salary = {0}
", emp1.Salary);

      SerialEmployee emp2 = RecvData(strm);
      Console.WriteLine("emp2.EmployeeID = {0}", emp2.EmployeeID);
      Console.WriteLine("emp2.LastName = {0}", emp2.LastName);
      Console.WriteLine("emp2.FirstName = {0}", emp2.FirstName);
      Console.WriteLine("emp2.YearsService = {0}", emp2.YearsService);
      Console.WriteLine("emp2.Salary = {0}", emp2.Salary);
      strm.Close();
      server.Stop();
   }

   public static void Main()
   {
      BetterDataRcvr bdr = new BetterDataRcvr();
   }
}



[Serializable]
public class SerialEmployee
{
   public int EmployeeID;
   public string LastName;
   public string FirstName;
   public int YearsService;
   public double Salary;

   public SerialEmployee()
   {
      EmployeeID = 0;
      LastName = null;
      FirstName = null;
      YearsService = 0;
      Salary = 0.0;
   }
}

           
          


Cryp Data Sender

image_pdfimage_print
   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.Security;
using System.Security.Cryptography;
using System.Text;

public class CryptoDataSender
{
   private void SendData(NetworkStream strm, SerialEmployee emp)
   {
      IFormatter formatter = new SoapFormatter();
      MemoryStream memstrm = new MemoryStream();

      byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
      byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};

      TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
      CryptoStream csw = new CryptoStream(memstrm, tdes.CreateEncryptor(Key, IV), CryptoStreamMode.Write);

      formatter.Serialize(csw, emp);
      csw.FlushFinalBlock();
      byte[] data = memstrm.GetBuffer();
      int memsize = (int)memstrm.Length;
      byte[] size = BitConverter.GetBytes(memsize);
      strm.Write(size, 0, 4);
      strm.Write(data, 0, (int)memsize);
      strm.Flush();
      csw.Close();
      memstrm.Close();
   }

   public CryptoDataSender()
   {
      SerialEmployee emp1 = new SerialEmployee();
      SerialEmployee emp2 = new SerialEmployee();

      emp1.EmployeeID = 1;
      emp1.LastName = "Blum";
      emp1.FirstName = "Katie Jane";
      emp1.YearsService = 12;
      emp1.Salary = 35000.50;

      emp2.EmployeeID = 2;
      emp2.LastName = "Blum";
      emp2.FirstName = "Jessica";
      emp2.YearsService = 9;
      emp2.Salary = 23700.30;

      TcpClient client = new TcpClient("127.0.0.1", 9050);
      NetworkStream strm = client.GetStream();

      SendData(strm, emp1);
      SendData(strm, emp2);
      strm.Close();
      client.Close();
   }

   public static void Main()
   {
      CryptoDataSender cds = new CryptoDataSender();
   }
}


[Serializable]
public class SerialEmployee
{
   public int EmployeeID;
   public string LastName;
   public string FirstName;
   public int YearsService;
   public double Salary;

   public SerialEmployee()
   {
      EmployeeID = 0;
      LastName = null;
      FirstName = null;
      YearsService = 0;
      Salary = 0.0;
   }
}


           
          


Cryp Data Receiver

image_pdfimage_print
   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.Security;
using System.Security.Cryptography;
using System.Text;

public class CryptoDataRcvr
{
   private SerialEmployee RecvData(NetworkStream strm)
   {
      MemoryStream memstrm = new MemoryStream();

      byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
                    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
      byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
                   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};

      TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
      CryptoStream csw = new CryptoStream(memstrm, tdes.CreateDecryptor(Key, IV),
                         CryptoStreamMode.Write);

      byte[] data = new byte[2048];
      int recv = strm.Read(data, 0, 4);
      int size = BitConverter.ToInt32(data, 0);
      int offset = 0;
      while(size > 0)
      {
         recv = strm.Read(data, 0, size);
         csw.Write(data, offset, recv);
         offset += recv;
         size -= recv;
      }
      csw.FlushFinalBlock();
      IFormatter formatter = new SoapFormatter();
      memstrm.Position = 0;
      SerialEmployee emp = (SerialEmployee)formatter.Deserialize(memstrm);
      memstrm.Close();
      return emp;
   }      

   public CryptoDataRcvr()
   {
      TcpListener server = new TcpListener(9050);
      server.Start();
      Console.WriteLine("Waiting for a client...");
      TcpClient client = server.AcceptTcpClient();
      NetworkStream strm = client.GetStream();

      SerialEmployee emp1 = RecvData(strm);
      Console.WriteLine("emp1.EmployeeID = {0}", emp1.EmployeeID);
      Console.WriteLine("emp1.LastName = {0}", emp1.LastName);
      Console.WriteLine("emp1.FirstName = {0}", emp1.FirstName);
      Console.WriteLine("emp1.YearsService = {0}", emp1.YearsService);
      Console.WriteLine("emp1.Salary = {0}
", emp1.Salary);

      SerialEmployee emp2 = RecvData(strm);
      Console.WriteLine("emp2.EmployeeID = {0}", emp2.EmployeeID);
      Console.WriteLine("emp2.LastName = {0}", emp2.LastName);
      Console.WriteLine("emp2.FirstName = {0}", emp2.FirstName);
      Console.WriteLine("emp2.YearsService = {0}", emp2.YearsService);
      Console.WriteLine("emp2.Salary = {0}", emp2.Salary);
      strm.Close();
      server.Stop();
   }

   public static void Main()
   {
      CryptoDataRcvr cdr = new CryptoDataRcvr();
   }
}

[Serializable]
public class SerialEmployee
{
   public int EmployeeID;
   public string LastName;
   public string FirstName;
   public int YearsService;
   public double Salary;

   public SerialEmployee()
   {
      EmployeeID = 0;
      LastName = null;
      FirstName = null;
      YearsService = 0;
      Salary = 0.0;
   }
}


           
          


CryptoStream demo

image_pdfimage_print
   

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/

using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Text;

public class CryptoTest
{
   public static void Main()
   {
      Console.Write("Enter phrase to encrypt: ");
      string phrase = Console.ReadLine();
      MemoryStream memstrm = new MemoryStream();

      byte[] Key = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
                    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
      byte[] IV = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
                   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};

      TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
      CryptoStream csw = new CryptoStream(memstrm,
                     tdes.CreateEncryptor(Key, IV), CryptoStreamMode.Write);

      csw.Write(Encoding.ASCII.GetBytes(phrase), 0, phrase.Length);
      csw.FlushFinalBlock();
      byte[] cryptdata = memstrm.GetBuffer();
      Console.WriteLine("Encrypted: {0}",
              Encoding.ASCII.GetString(cryptdata, 0, (int)memstrm.Length));

      memstrm.Position = 0;
      byte[] data = new byte[1024];

      CryptoStream csr = new CryptoStream(memstrm,
                     tdes.CreateDecryptor(Key, IV), CryptoStreamMode.Read);
      int recv = csr.Read(data, 0, data.Length);
      string newphrase = Encoding.ASCII.GetString(data, 0, recv);
      Console.WriteLine("Decrypted: {0}", newphrase);
      csr.Close();
      csw.Close();
      memstrm.Close();
   }
}

           
          


Examine Cookies

image_pdfimage_print

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

/* Examine Cookies.

To see what cookies a Web Site uses,
specify its name on the command line.
For example, if you call this program
Cookie, then

Cookie http://MSN.COM

displays the cookies associated with MSN.COM.
*/

using System;
using System.Net;

public class CookieDemo {
public static void Main(string[] args) {

if(args.Length != 1) {
Console.WriteLine(“Usage: CookieDemo “);
return ;
}

// Create a WebRequest to the specified URI.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create(args[0]);

// Get an empty cookie container.
req.CookieContainer = new CookieContainer();

// Send the request and return the response.
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();

// Display the cookies.
Console.WriteLine(“Number of cookies: ” +
resp.Cookies.Count);
Console.WriteLine(“{0,-20}{1}”, “Name”, “Value”);

for(int i=0; i < resp.Cookies.Count; i++) Console.WriteLine("{0, -20}{1}", resp.Cookies[i].Name, resp.Cookies[i].Value); // Close the Response. resp.Close(); } } [/csharp]

Chat Application

image_pdfimage_print


   

/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury, 
   Zach Greenvoss, Shripad Kulkarni, Neil Whitlow

Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Threading;

namespace Wrox.WindowsGUIProgramming.Chapter9
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class ChatApplication : System.Windows.Forms.Form
    {
        internal System.Windows.Forms.ListBox listBox1;
        private System.Windows.Forms.TextBox txtMessage;
        private System.Windows.Forms.Button btSend;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;
        private System.Windows.Forms.ComboBox cmdHost;
        private System.Windows.Forms.CheckBox chkSuspendClient;

        private PeerConnection p = null;

        public ChatApplication()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            p = new PeerConnection(4048, listBox1, cmdHost);
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.txtMessage = new System.Windows.Forms.TextBox();
            this.btSend = new System.Windows.Forms.Button();
            this.cmdHost = new System.Windows.Forms.ComboBox();
            this.chkSuspendClient = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();
            // 
            // listBox1
            // 
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(688, 394);
            this.listBox1.TabIndex = 0;
            // 
            // txtMessage
            // 
            this.txtMessage.Location = new System.Drawing.Point(8, 408);
            this.txtMessage.Name = "txtMessage";
            this.txtMessage.Size = new System.Drawing.Size(576, 20);
            this.txtMessage.TabIndex = 1;
            this.txtMessage.Text = "";
            // 
            // btSend
            // 
            this.btSend.Location = new System.Drawing.Point(608, 408);
            this.btSend.Name = "btSend";
            this.btSend.TabIndex = 2;
            this.btSend.Text = "Send";
            this.btSend.Click += new System.EventHandler(this.btSend_Click);
            // 
            // cmdHost
            // 
            this.cmdHost.Location = new System.Drawing.Point(8, 432);
            this.cmdHost.Name = "cmdHost";
            this.cmdHost.Size = new System.Drawing.Size(520, 21);
            this.cmdHost.TabIndex = 3;
            this.cmdHost.Text = "localhost";
            // 
            // chkSuspendClient
            // 
            this.chkSuspendClient.Location = new System.Drawing.Point(544, 432);
            this.chkSuspendClient.Name = "chkSuspendClient";
            this.chkSuspendClient.Size = new System.Drawing.Size(152, 24);
            this.chkSuspendClient.TabIndex = 4;
            this.chkSuspendClient.Text = "Suspend Client";
            this.chkSuspendClient.CheckedChanged += new System.EventHandler(this.chkSuspendClient_CheckedChanged);
            // 
            // ChatApplication
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(688, 462);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.chkSuspendClient,
                                                                          this.cmdHost,
                                                                          this.btSend,
                                                                          this.txtMessage,
                                                                          this.listBox1});
            this.MaximizeBox = false;
            this.Name = "ChatApplication";
            this.Text = "Chat!";
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new ChatApplication());
        }

        private void btSend_Click(object sender, System.EventArgs e)
        {
            p.Write(txtMessage.Text);
        }

        private void chkSuspendClient_CheckedChanged(object sender, System.EventArgs e)
        {
            if(chkSuspendClient.Checked==true)
            {
                p.Enabled = true;
            }
            else
            {
                p.Enabled = false;
            }
        }
    }


    public class PeerConnection
    {
        private System.Net.Sockets.TcpListener peerListener = null;
        private System.Net.Sockets.TcpClient peerClient = null;
        private System.Net.Sockets.NetworkStream netStream = null;
        private Thread t1 = null;
        private IntPtr formHandle;
        private int port = 0;
        private bool clientEnabled = true;
        private ListBox lb;
        private ComboBox cmb;

        public PeerConnection(int port, ListBox formHandle, ComboBox cmdHost)
        {
            this.port = port;
            this.lb = formHandle;
            this.cmb = cmdHost;
            t1 = new Thread(new ThreadStart(CreateListener));
            t1.Name = "Listener Thread";
            t1.Priority = ThreadPriority.AboveNormal;
            t1.Start();
        }

        delegate void CallbackListbox(string message);

        void SetListboxString(string item)
        {
            lb.Items.Add(item);
        }

        private void CreateListener()
        {
            Socket tc = null;

            peerListener = new TcpListener(port);
            peerListener.Start();

            CallbackListbox clb = new CallbackListbox(SetListboxString);
            while(true)
            {
                tc = peerListener.AcceptSocket();
                byte[] byMessage = new byte[256];
                Thread.Sleep(500);
                int iLength = tc.Receive(byMessage, 0, byMessage.Length, SocketFlags.None); 
                if(iLength>0)
                {
                    string message = System.Text.Encoding.Default.GetString(byMessage);
                    try
                    {
                        if(lb.InvokeRequired) lb.Invoke(clb, new object[]{message});
                    }
                    catch(Exception e)
                    {
                        message = e.Message;
                    }
                    finally
                    {
                        System.Diagnostics.Debug.WriteLine(message);
                    }
                }
            }
        }

        private void CreateClient(object message)
        {
            peerClient = new TcpClient();
            peerClient.Connect(cmb.SelectedText, port);

            netStream = peerClient.GetStream();

            StreamWriter sw = new StreamWriter(netStream);
            sw.Write((string)message);
            sw.Flush();

            peerClient.Close();
        }

        internal void Write(string message)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(CreateClient), message);
        }

        internal bool Enabled
        {
            set
            {
                if(t1.ThreadState==ThreadState.Suspended&amp;&amp;value==true)
                {
                    t1.Resume();
                }
                else if(t1.ThreadState!=ThreadState.Suspended&amp;&amp;value==false)
                {
                    t1.Suspend();
                }
                clientEnabled = value;
            }
            get
            {
                return clientEnabled;
            }   
        }
    }
}