Click here to Skip to main content
15,887,596 members
Articles / Programming Languages / C#
Tip/Trick

UDP based Windows chat application

Rate me:
Please Sign up or sign in to vote.
2.71/5 (4 votes)
13 Jul 2012CPOL 26.7K   9   3
UDP based chat application.

Introduction

The User Datagram Protocol (UDP) is one of the core members of the Internet Protocol Suite, the set of network protocols used for the Internet. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network without requiring prior communication to set up special transmission channels or data paths.

This is a Windows application which keeps listening to all unallocated ports and keeps sending to the network through a specific port.

Using the code

Image 1

This is the login screen, and the next window is the chat window.

Image 2

The code used for the login screen:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;

namespace Chat
{
    public partial class Login : Form
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Login"/> class.
        /// </summary>
        public Login()
        {
            InitializeComponent();
            txtUserName.Focus();
        }

        /// <summary>
        /// Handles the Click event of the btnConnect control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/>
        ///         instance containing the event data.</param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            LoginMethod();
        }

        /// <summary>
        /// Logins the method.
        /// </summary>
        private void LoginMethod()
        {
            if (!string.IsNullOrEmpty(txtUserName.Text))
            {
                UdpClient sendClient = new UdpClient();
                Byte[] Text = Encoding.ASCII.GetBytes(txtUserName.Text + " Joined the room...");
                IPEndPoint sendEndPoint = new IPEndPoint(IPAddress.Broadcast, 1800);
                sendClient.Send(Text, Text.Length, sendEndPoint);
                sendClient.Close();

                this.Hide();
                Message m = new Message();
                m.name = txtUserName.Text;
                m.Show();
            }
        }

        /// <summary>
        /// Handles the KeyDown event of the txtUserName control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/>
        ///       instance containing the event data.</param>
        private void txtUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                LoginMethod();
            }
        }

        /// <summary>
        /// Handles the Load event of the Login control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/>
        ///           instance containing the event data.</param>
        private void Login_Load(object sender, EventArgs e)
        {
            txtUserName.Focus();
        }
    }
}

The code for the messenger screen:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace Chat
{
    public partial class Message : Form
    {
        UdpClient receiveClient = new UdpClient(1800);
        IPEndPoint receiveEndPint = new IPEndPoint(IPAddress.Any, 0);
        public string name;

        /// <summary>
        /// Initializes a new instance of the <see cref="Message"/> class.
        /// </summary>
        public Message()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Handles the Load event of the Message control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Message_Load(object sender, EventArgs e)
        {
            txtMessageWindow.Text = name + " Joined the room...";   
            Thread rec = new Thread(ReceiveMessageFn);
            rec.Start();
            txtTextMessage.Focus();
        }

        /// <summary>
        /// Receives the message fn.
        /// </summary>
        private void ReceiveMessageFn()
        {
            try
            {
                while (true)
                {
                    Byte[] receve = receiveClient.Receive(ref receiveEndPint);
                    string message = Encoding.ASCII.GetString(receve);

                    if (message == name + " logged out...")
                    {
                        break;
                    }
                    else
                    {
                        if (message.Contains(name + " says >>"))
                        {
                            message = message.Replace(name + " says >>", "Me says >>");
                        }

                        ShowMessage(message);
                    }
                }

                Thread.CurrentThread.Abort();
                Application.Exit();

            }
            catch(ThreadAbortException ex)
            {               
                Application.Exit();
                
            }
        }

        /// <summary>
        /// Handles the KeyDown event of the txtTextMessage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param>
        private void txtTextMessage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(txtTextMessage.Text))
                {
                    string data = name + " says >> " + txtTextMessage.Text;
                    SendMessage(data);
                }
            }
        }

        /// <summary>
        /// Sends the message.
        /// </summary>
        /// <param name="data">The data.</param>
        private void SendMessage( string data)
        {
            UdpClient sendClient = new UdpClient();
            Byte[] message = Encoding.ASCII.GetBytes(data);
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, 1800);
            sendClient.Send(message, message.Length, endPoint);
            sendClient.Close();

            txtTextMessage.Clear();
            txtTextMessage.Focus();
        }

        /// <summary>
        /// Handles the Click event of the btnSend control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtTextMessage.Text))
            {
                string data = name + " says >> " + txtTextMessage.Text;
                SendMessage(data);
            }
        }

        /// <summary>
        /// Shows the message.
        /// </summary>
        /// <param name="message">The message.</param>
        private void ShowMessage(string message)
        {
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(delegate() { ShowMessage(message); }));
            else
            {
                txtMessageWindow.Text = txtMessageWindow.Text + Environment.NewLine + message;
                txtMessageWindow.SelectionStart = txtMessageWindow.TextLength;
                txtMessageWindow.ScrollToCaret();
                txtMessageWindow.Refresh();
            }
        }

        /// <summary>
        /// Handles the FormClosing event of the Message control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see
        ///    cref="System.Windows.Forms.FormClosingEventArgs"/>
        ///    instance containing the event data.</param>
        private void Message_FormClosing(object sender, FormClosingEventArgs e)
        {
            string data = name + " logged out...";
            SendMessage(data);           
        }

        /// <summary>
        /// Handles the KeyDown event of the txtMessageWindow control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see
        ///    cref="System.Windows.Forms.KeyEventArgs"/>
        ///    instance containing the event data.</param>
        private void txtMessageWindow_KeyDown(object sender, KeyEventArgs e)
        {
            e.SuppressKeyPress = true;            
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I am a software developer with a passion to develop innovative ideas.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Dave Kreskowiak15-Jul-12 2:41
mveDave Kreskowiak15-Jul-12 2:41 
GeneralCheck out my blog for more details Pin
Christopher John Paul11-Jul-12 23:46
Christopher John Paul11-Jul-12 23:46 
GeneralRe: Check out my blog for more details Pin
Dave Kreskowiak15-Jul-12 2:38
mveDave Kreskowiak15-Jul-12 2:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.