Solved

UDP broadcast client and server in one application?

Posted on 2004-09-27
1
587 Views
Last Modified: 2008-01-09
I need a single C# program that runs as both a client and server simultaneously. I would like to send a UDP broadcast containing the contents of a WinForms TextBox whenever a button is pressed, and display the contents of the message that was broadcast in a MessageBox on all the clients who receive the broadcast. Basically, I'm envisioning the following:

-Simple UI with TextBox and "send" Button that launches the Listener thread (mentioned below) when it comes up
-Function that sends a datagram with the contents of the textbox via UDP broadcast
-Listener thread that listens for UDP packets on a specific port (let's go with 40040) that throws up a MessageBox with the contents of the message every time one is received

Thanks in advance for your help!
0
Comment
Question by:newcomguy
1 Comment
 
LVL 19

Accepted Solution

by:
drichards earned 500 total points
ID: 12166015
Here's a REALLY simple version.  It allows you to have a separate "Send To" port so you can run two instances on the same machine.  It uses the thread pool to display the message boxes so you can have more than one arrive.  Also allows you to send while boxes are up.

A better version would do subnet broadcasts, but you'd have to gather a bit of information about the interfaces on the machine to be able to do that.
-------------------------------------------

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;

namespace Messaging
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private System.Windows.Forms.TextBox textBox1;
            private System.Windows.Forms.TextBox textBox2;
            private System.Windows.Forms.Label label1;
            private System.Windows.Forms.Button button1;
            private System.Windows.Forms.Button button2;
            private System.Net.Sockets.Socket socket;
            private byte[] incoming_msg;
            private System.Net.IPEndPoint remoteEP;
            private System.AsyncCallback rcvCallback;
            private System.Threading.WaitCallback showMsg;
            private const int MSG_LENGTH = 1024;
            private System.Windows.Forms.Label label2;
            private System.Windows.Forms.TextBox textBox3;

            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

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

                  incoming_msg = new byte[MSG_LENGTH];
                  remoteEP = new IPEndPoint(IPAddress.Any, 0);
                  rcvCallback = new AsyncCallback(this.ReceiveCallback);
                  showMsg = new System.Threading.WaitCallback(this.ShowMessage);
                  button1.Enabled = false;
            }

            /// <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.textBox1 = new System.Windows.Forms.TextBox();
                  this.textBox2 = new System.Windows.Forms.TextBox();
                  this.label1 = new System.Windows.Forms.Label();
                  this.button1 = new System.Windows.Forms.Button();
                  this.button2 = new System.Windows.Forms.Button();
                  this.label2 = new System.Windows.Forms.Label();
                  this.textBox3 = new System.Windows.Forms.TextBox();
                  this.SuspendLayout();
                  //
                  // textBox1
                  //
                  this.textBox1.AcceptsReturn = true;
                  this.textBox1.Location = new System.Drawing.Point(8, 56);
                  this.textBox1.Multiline = true;
                  this.textBox1.Name = "textBox1";
                  this.textBox1.Size = new System.Drawing.Size(592, 96);
                  this.textBox1.TabIndex = 0;
                  this.textBox1.Text = "";
                  //
                  // textBox2
                  //
                  this.textBox2.Location = new System.Drawing.Point(80, 20);
                  this.textBox2.Name = "textBox2";
                  this.textBox2.Size = new System.Drawing.Size(72, 20);
                  this.textBox2.TabIndex = 1;
                  this.textBox2.Text = "40040";
                  //
                  // label1
                  //
                  this.label1.Location = new System.Drawing.Point(24, 24);
                  this.label1.Name = "label1";
                  this.label1.Size = new System.Drawing.Size(56, 16);
                  this.label1.TabIndex = 2;
                  this.label1.Text = "UDP Port:";
                  //
                  // button1
                  //
                  this.button1.Location = new System.Drawing.Point(240, 168);
                  this.button1.Name = "button1";
                  this.button1.TabIndex = 3;
                  this.button1.Text = "Send";
                  this.button1.Click += new System.EventHandler(this.button1_Click);
                  //
                  // button2
                  //
                  this.button2.Location = new System.Drawing.Point(184, 19);
                  this.button2.Name = "button2";
                  this.button2.TabIndex = 4;
                  this.button2.Text = "Start";
                  this.button2.Click += new System.EventHandler(this.button2_Click);
                  //
                  // label2
                  //
                  this.label2.Location = new System.Drawing.Point(328, 24);
                  this.label2.Name = "label2";
                  this.label2.Size = new System.Drawing.Size(80, 16);
                  this.label2.TabIndex = 6;
                  this.label2.Text = "Send To Port:";
                  //
                  // textBox3
                  //
                  this.textBox3.Location = new System.Drawing.Point(408, 20);
                  this.textBox3.Name = "textBox3";
                  this.textBox3.Size = new System.Drawing.Size(72, 20);
                  this.textBox3.TabIndex = 5;
                  this.textBox3.Text = "40040";
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(608, 198);
                  this.Controls.Add(this.label2);
                  this.Controls.Add(this.textBox3);
                  this.Controls.Add(this.button2);
                  this.Controls.Add(this.button1);
                  this.Controls.Add(this.label1);
                  this.Controls.Add(this.textBox2);
                  this.Controls.Add(this.textBox1);
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.ResumeLayout(false);

            }
            #endregion

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

            private void ShowMessage(object msg)
            {
                  MessageBox.Show((string) msg);
            }

            private void ReceiveCallback(IAsyncResult ar)
            {
                  Socket socket = (Socket)ar.AsyncState;
                  EndPoint ep = (EndPoint)remoteEP;
                  int dataLength = socket.EndReceiveFrom(ar, ref ep);
                  string msg = System.Text.ASCIIEncoding.ASCII.GetString(incoming_msg, 0, dataLength);
                  System.Threading.ThreadPool.QueueUserWorkItem(showMsg, msg);
                  socket.BeginReceiveFrom(incoming_msg, 0, MSG_LENGTH, SocketFlags.None, ref ep, rcvCallback, socket);
            }

            private void button2_Click(object sender, System.EventArgs e)
            {
                  if ( socket == null )
                  {
                        button2.Text = "Stop";
                        socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                        socket.Bind(new System.Net.IPEndPoint(IPAddress.Any, int.Parse(textBox2.Text)));
                        
                        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                        EndPoint ep = (EndPoint)remoteEP;
                        socket.BeginReceiveFrom(incoming_msg, 0, MSG_LENGTH, SocketFlags.None, ref ep, rcvCallback, socket);
                        button1.Enabled = true;
                  }
                  else
                  {
                        socket.Close();
                        socket = null;
                        button2.Text = "Start";
                        button1.Enabled = false;
                  }
            }

            private void button1_Click(object sender, System.EventArgs e)
            {
                  IPEndPoint ep = new IPEndPoint(IPAddress.Broadcast, int.Parse(textBox3.Text));
                  byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(textBox1.Text);
                  socket.SendTo(buf, ep);
                  textBox1.Clear();
            }
      }
}
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now