Friday, July 6, 2012

Chat Application Without Server - UDP

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 communications to set up special transmission channels or data paths.

This is a windows application which keep listening to all unallocated ports and keep sending to the network throuhg a specific port.

this is the login screen.
and the next window is thw chat window.



The codes used for login screen is

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();
        }
    }
}


For the chat window is

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;           
        }
    }
}

1 comment:

  1. nice code .
    but if i want to display all users username

    ReplyDelete