Solved

UDP broadcast client and server in one application?

Posted on 2004-09-27
1
594 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

Secure Your Active Directory - April 20, 2017

Active Directory plays a critical role in your company’s IT infrastructure and keeping it secure in today’s hacker-infested world is a must.
Microsoft published 300+ pages of guidance, but who has the time, money, and resources to implement? Register now to find an easier way.

Question has a verified solution.

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

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

679 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