Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

UDP broadcast client and server in one application?

Posted on 2004-09-27
1
Medium Priority
?
604 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 19

Accepted Solution

by:
drichards earned 2000 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

688 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