Csharp/C Sharp/Network/Chat

Материал из .Net Framework эксперт
Версия от 11:47, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Chat Application

/*
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.ruponentModel;
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.ruponentModel.Container components = null;
        private System.Windows.Forms.ruboBox 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.ruboBox();
            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&&value==true)
                {
                    t1.Resume();
                }
                else if(t1.ThreadState!=ThreadState.Suspended&&value==false)
                {
                    t1.Suspend();
                }
                clientEnabled = value;
            }
            get
            {
                return clientEnabled;
            }   
        }
    }
}


Multicast Chat

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
public class MulticastChat : Form
{
   TextBox newText;
   ListBox results;
   Socket sock;
   Thread receiver;
   IPEndPoint multiep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
   public MulticastChat()
   {
      Text = "Multicast Chat Program";
      Size = new Size(400, 380);
      Label label1 = new Label();
      label1.Parent = this;
      label1.Text = "Enter text string:";
      label1.AutoSize = true;
      label1.Location = new Point(10, 30);
      newText = new TextBox();
      newText.Parent = this;
      newText.Size = new Size(200, 2 * Font.Height);
      newText.Location = new Point(10, 55);
      results = new ListBox();
      results.Parent = this;
      results.Location = new Point(10, 85);
      results.Size = new Size(360, 18 * Font.Height);
      Button sendit = new Button();
      sendit.Parent = this;
      sendit.Text = "Send";
      sendit.Location = new Point(220,52);
      sendit.Size = new Size(5 * Font.Height, 2 * Font.Height);
      sendit.Click += new EventHandler(ButtonSendOnClick);
      Button closeit = new Button();
      closeit.Parent = this;
      closeit.Text = "Close";
      closeit.Location = new Point(290, 52);
      closeit.Size = new Size(5 * Font.Height, 2 * Font.Height);
      closeit.Click += new EventHandler(ButtonCloseOnClick);
      sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
      IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
      sock.Bind(iep);
      sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.100.0.1")));
      receiver = new Thread(new ThreadStart(packetReceive));
      receiver.IsBackground = true;
      receiver.Start();
   }
   void ButtonSendOnClick(object obj, EventArgs ea)
   {
      byte[] message = Encoding.ASCII.GetBytes(newText.Text);
      newText.Clear();
      sock.SendTo(message, SocketFlags.None, multiep);
   }
   void ButtonCloseOnClick(object obj, EventArgs ea)
   {
      receiver.Abort();
      sock.Close();
      Close();
   }
   void packetReceive()
   {
      EndPoint ep = (EndPoint)multiep;
      byte[] data = new byte[1024];
      string stringData;
      int recv;
      while (true)
      {
         recv = sock.ReceiveFrom(data, ref ep);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         results.Items.Add("from " + ep.ToString() + ":  " + stringData);
      }
   }
   public static void Main()
   {
      Application.Run(new MulticastChat());
   }
}


New Tcp Chat

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

public class NewTcpChat : Form
{
   private static TextBox newText;
   private static ListBox results;
   private static ListBox hosts;
   private static Socket client;
   private static byte[] data = new byte[1024];
   public NewTcpChat()
   {
      Text = "New TCP Chat Program";
      Size = new Size(400, 380);
      
      Label label1 = new Label();
      label1.Parent = this;
      label1.Text = "Enter text string:";
      label1.AutoSize = true;
      label1.Location = new Point(10, 30);
      newText = new TextBox();
      newText.Parent = this;
      newText.Size = new Size(200, 2 * Font.Height);
      newText.Location = new Point(10, 55);
      results = new ListBox();
      results.Parent = this;
      results.Location = new Point(10, 85);
      results.Size = new Size(360, 10 * Font.Height);
      Label label2 = new Label();
      label2.Parent = this;
      label2.Text = "Active hosts";
      label2.AutoSize = true;
      label2.Location = new Point(10, 240);
      hosts = new ListBox();
      hosts.Parent = this;
      hosts.Location = new Point(10, 255);
      hosts.Size = new Size(360, 5 * Font.Height);
      Button sendit = new Button();
      sendit.Parent = this;
      sendit.Text = "Send";
      sendit.Location = new Point(220,52);
      sendit.Size = new Size(5 * Font.Height, 2 * Font.Height);
      sendit.Click += new EventHandler(ButtonSendOnClick);
      Button connect = new Button();
      connect.Parent = this;
      connect.Text = "Connect";
      connect.Location = new Point(295, 20);
      connect.Size = new Size(6 * Font.Height, 2 * Font.Height);
      connect.Click += new EventHandler(ButtonConnectOnClick);
      Button listen = new Button();
      listen.Parent = this;
      listen.Text = "Listen";
      listen.Location = new Point(295,52);
      listen.Size = new Size(6 * Font.Height, 2 * Font.Height);
      listen.Click += new EventHandler(ButtonListenOnClick);
      Thread fh = new Thread(new ThreadStart(findHosts));
      fh.IsBackground = true;
      fh.Start();
   }
   void ButtonListenOnClick(object obj, EventArgs ea)
   {
      results.Items.Add("Listening for a client...");
      Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
      newsock.Bind(iep);
      newsock.Listen(5);
      newsock.BeginAccept(new AsyncCallback(AcceptConn), newsock);
      Thread advertise = new Thread(new ThreadStart(srvrAdvertise));
      advertise.IsBackground = true;
      advertise.Start();
   }
   void ButtonConnectOnClick(object obj, EventArgs ea)
   {
      results.Items.Add("Connecting...");
      client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      string selectedhost = (string)hosts.SelectedItem;
      string[] hostarray = selectedhost.Split(":");
      IPEndPoint iep = new IPEndPoint(IPAddress.Parse(hostarray[1]), 9050);
      client.BeginConnect(iep, new AsyncCallback(Connected), client);
   }
   void ButtonSendOnClick(object obj, EventArgs ea)
   {
      byte[] message = Encoding.ASCII.GetBytes(newText.Text);
      newText.Clear();
      client.BeginSend(message, 0, message.Length, 0, new AsyncCallback(SendData), client);
   }
   void AcceptConn(IAsyncResult iar)
   {
      Socket oldserver = (Socket)iar.AsyncState;
      client = oldserver.EndAccept(iar);
      results.Items.Add("Connection from: " + client.RemoteEndPoint.ToString());
      Thread receiver = new Thread(new ThreadStart(ReceiveData));
      receiver.IsBackground = true;
      receiver.Start();
   }
   void Connected(IAsyncResult iar)
   {
      try
      {
         client.EndConnect(iar);
         results.Items.Add("Connected to: " + client.RemoteEndPoint.ToString());
         Thread receiver = new Thread(new ThreadStart(ReceiveData));
         receiver.IsBackground = true;
         receiver.Start();
      } catch (SocketException)
      {
         results.Items.Add("Error connecting");
      }
   }
   void SendData(IAsyncResult iar)
   {
      Socket remote = (Socket)iar.AsyncState;
      int sent = remote.EndSend(iar);
   }
   void ReceiveData()
   {
      int recv;
      string stringData;
      while (true)
      {
         recv = client.Receive(data);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         if (stringData == "bye")
            break;
         results.Items.Add(stringData);
      }
      stringData = "bye";
      byte[] message = Encoding.ASCII.GetBytes(stringData);
      client.Send(message);
      client.Close();
      results.Items.Add("Connection stopped");
      return;
   }
   void srvrAdvertise()
   {
      Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
      server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
      IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9051);
      byte[] hostname = Encoding.ASCII.GetBytes(Dns.GetHostName());
      while (true)
      {
         server.SendTo(hostname, iep);
         Thread.Sleep(60000);
      }
   }
   void findHosts()
   {
      while(true)
      {
         Socket remoteHosts = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
         IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9051);
         EndPoint ep = (EndPoint)iep;
         remoteHosts.Bind(iep);
         byte[] data = new byte[1024];
         int recv = remoteHosts.ReceiveFrom(data, ref ep);
         string stringData = Encoding.ASCII.GetString(data, 0, recv);
         string entry = stringData + ":" + ep.ToString();
         if (!hosts.Items.Contains(entry))
            hosts.Items.Add(entry);
      }
   }
   public static void Main()
   {
      Application.Run(new NewTcpChat());
   }
}


Tcp Chat

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

public class TcpChat : Form
{
   private static TextBox newText;
   private static ListBox results;
   private static Socket client;
   private static byte[] data = new byte[1024];
   public TcpChat()
   {
      Text = "TCP Chat Program";
      Size = new Size(400, 380);
      
      Label label1 = new Label();
      label1.Parent = this;
      label1.Text = "Enter text string:";
      label1.AutoSize = true;
      label1.Location = new Point(10, 30);
      newText = new TextBox();
      newText.Parent = this;
      newText.Size = new Size(200, 2 * Font.Height);
      newText.Location = new Point(10, 55);
      results = new ListBox();
      results.Parent = this;
      results.Location = new Point(10, 85);
      results.Size = new Size(360, 18 * Font.Height);
      Button sendit = new Button();
      sendit.Parent = this;
      sendit.Text = "Send";
      sendit.Location = new Point(220,52);
      sendit.Size = new Size(5 * Font.Height, 2 * Font.Height);
      sendit.Click += new EventHandler(ButtonSendOnClick);
      Button connect = new Button();
      connect.Parent = this;
      connect.Text = "Connect";
      connect.Location = new Point(295, 20);
      connect.Size = new Size(6 * Font.Height, 2 * Font.Height);
      connect.Click += new EventHandler(ButtonConnectOnClick);
      Button listen = new Button();
      listen.Parent = this;
      listen.Text = "Listen";
      listen.Location = new Point(295,52);
      listen.Size = new Size(6 * Font.Height, 2 * Font.Height);
      listen.Click += new EventHandler(ButtonListenOnClick);
   }
   void ButtonListenOnClick(object obj, EventArgs ea)
   {
      results.Items.Add("Listening for a client...");
      Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
      newsock.Bind(iep);
      newsock.Listen(5);
      newsock.BeginAccept(new AsyncCallback(AcceptConn), newsock);
   }
   void ButtonConnectOnClick(object obj, EventArgs ea)
   {
      results.Items.Add("Connecting...");
      client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
      client.BeginConnect(iep, new AsyncCallback(Connected), client);
   }
   void ButtonSendOnClick(object obj, EventArgs ea)
   {
      byte[] message = Encoding.ASCII.GetBytes(newText.Text);
      newText.Clear();
      client.BeginSend(message, 0, message.Length, 0, new AsyncCallback(SendData), client);
   }
   void AcceptConn(IAsyncResult iar)
   {
      Socket oldserver = (Socket)iar.AsyncState;
      client = oldserver.EndAccept(iar);
      results.Items.Add("Connection from: " + client.RemoteEndPoint.ToString());
      Thread receiver = new Thread(new ThreadStart(ReceiveData));
      receiver.Start();
   }
   void Connected(IAsyncResult iar)
   {
      try
      {
         client.EndConnect(iar);
         results.Items.Add("Connected to: " + client.RemoteEndPoint.ToString());
         Thread receiver = new Thread(new ThreadStart(ReceiveData));
         receiver.Start();
      } catch (SocketException)
      {
         results.Items.Add("Error connecting");
      }
   }
   void SendData(IAsyncResult iar)
   {
      Socket remote = (Socket)iar.AsyncState;
      int sent = remote.EndSend(iar);
   }
   void ReceiveData()
   {
      int recv;
      string stringData;
      while (true)
      {
         recv = client.Receive(data);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         if (stringData == "bye")
            break;
         results.Items.Add(stringData);
      }
      stringData = "bye";
      byte[] message = Encoding.ASCII.GetBytes(stringData);
      client.Send(message);
      client.Close();
      results.Items.Add("Connection stopped");
      return;
   }
   public static void Main()
   {
      Application.Run(new TcpChat());
   }
}