Solved

UDP broadcast client and server in one application?

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

816 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

13 Experts available now in Live!

Get 1:1 Help Now