Chat Application : Chat « Network « C# / C Sharp

C# / C Sharp
1. 2D Graphics
2. Class Interface
3. Collections Data Structure
4. Components
5. Data Types
6. Database ADO.net
7. Design Patterns
8. Development Class
9. Event
10. File Stream
11. Generics
12. GUI Windows Form
13. Language Basics
14. LINQ
15. Network
16. Office
17. Reflection
18. Regular Expressions
19. Security
20. Services Event
21. Thread
22. Web Services
23. Windows
24. XML
25. XML LINQ
Java
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
C# / C Sharp » Network » ChatScreenshots 
Chat Application
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.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 Disposebool disposing )
        {
            ifdisposing )
            {
                if (components != null
                {
                    components.Dispose();
                }
            }
            base.Disposedisposing );
        }

        #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(688394);
            this.listBox1.TabIndex = 0;
            // 
            // txtMessage
            // 
            this.txtMessage.Location = new System.Drawing.Point(8408);
            this.txtMessage.Name = "txtMessage";
            this.txtMessage.Size = new System.Drawing.Size(57620);
            this.txtMessage.TabIndex = 1;
            this.txtMessage.Text = "";
            // 
            // btSend
            // 
            this.btSend.Location = new System.Drawing.Point(608408);
            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(8432);
            this.cmdHost.Name = "cmdHost";
            this.cmdHost.Size = new System.Drawing.Size(52021);
            this.cmdHost.TabIndex = 3;
            this.cmdHost.Text = "localhost";
            // 
            // chkSuspendClient
            // 
            this.chkSuspendClient.Location = new System.Drawing.Point(544432);
            this.chkSuspendClient.Name = "chkSuspendClient";
            this.chkSuspendClient.Size = new System.Drawing.Size(15224);
            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(513);
            this.ClientSize = new System.Drawing.Size(688462);
            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.InvokeRequiredlb.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;
            }   
        }
    }
}


           
       
Related examples in the same category
1. Tcp ChatTcp Chat
2. New Tcp ChatNew Tcp Chat
3. Multicast ChatMulticast Chat
w___ww__.j__a_va__2s.___c___o___m | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.