Use UDP broadcast mode to write simple information transmission tool ~

Source: Internet
Author: User
Tags bool exit join return sleep split thread vars
Using the UdpClient class
This is the test code I wrote, for reference ~

Using System;
Using System.Drawing;
Using System.Collections;
Using System.ComponentModel;
Using System.Windows.Forms;
Using System.Data;
Using System.Globalization;
Using System.Net;
Using System.Net.Sockets;
Using System.Threading;
Using System.Text;

Namespace Udpwintest
{
<summary>
Summary description of the Form1.
</summary>
public class Form1:System.Windows.Forms.Form
{
Private System.Windows.Forms.Button btnstart;
Private System.Windows.Forms.Button Btnjoin;
Private System.Windows.Forms.TextBox Txtserverip;
Private System.Windows.Forms.Button button1;
Private System.Windows.Forms.TextBox txtmsgsend;
Private System.Windows.Forms.TextBox Txtmessagemain;
<summary>
The required designer variable.
</summary>
Private System.ComponentModel.Container components = null;

private static UdpClient m_client;

private static int listenerport = 80;
private static int senderport = 80;
private static int localport;
private static int remoteport;

private static string M_szhostname;

private static IPAddress m_groupaddress;
private static Iphostentry M_localhost;
private static IPEndPoint M_remoteep;
Private System.Windows.Forms.Button btnend;

private static bool M_done = FALSE;
Private System.Windows.Forms.Button btnclose;

Private Thread t = null;
Private Thread t2 = null;

Public Form1 ()
{
InitializeComponent ();
}

<summary>
Clean up all resources that are in use.
</summary>
protected override void Dispose (bool disposing)
{
if (disposing)
{
if (Components!= null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing);
}

Code generated #region the Windows forms Designer
<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</summary>
private void InitializeComponent ()
{
This.btnstart = new System.Windows.Forms.Button ();
This.btnjoin = new System.Windows.Forms.Button ();
This.txtserverip = new System.Windows.Forms.TextBox ();
This.txtmessagemain = new System.Windows.Forms.TextBox ();
This.txtmsgsend = new System.Windows.Forms.TextBox ();
This.button1 = new System.Windows.Forms.Button ();
This.btnend = new System.Windows.Forms.Button ();
This.btnclose = new System.Windows.Forms.Button ();
This. SuspendLayout ();
//
Btnstart
//
This.btnStart.Location = new System.Drawing.Point (16, 16);
This.btnStart.Name = "Btnstart";
This.btnStart.TabIndex = 0;
This.btnStart.Text = "Start";
This.btnStart.Click + = new System.EventHandler (This.btnstart_click);
//
Btnjoin
//
This.btnJoin.Location = new System.Drawing.Point (408, 16);
This.btnJoin.Name = "Btnjoin";
This.btnJoin.TabIndex = 1;
This.btnJoin.Text = "Join";
This.btnJoin.Click + = new System.EventHandler (This.btnjoin_click);
//
Txtserverip
//
This.txtServerIP.Location = new System.Drawing.Point (304, 16);
This.txtServerIP.Name = "Txtserverip";
This.txtServerIP.Size = new System.Drawing.Size (96, 21);
This.txtServerIP.TabIndex = 2;
This.txtServerIP.Text = "10.89.58.220";
//
Txtmessagemain
//
This.txtMessageMain.Location = new System.Drawing.Point (16, 48);
This.txtMessageMain.Multiline = true;
This.txtMessageMain.Name = "Txtmessagemain";
This.txtMessageMain.Size = new System.Drawing.Size (464, 184);
This.txtMessageMain.TabIndex = 3;
This.txtMessageMain.Text = "";
//
Txtmsgsend
//
This.txtMsgSend.Location = new System.Drawing.Point (16, 240);
This.txtMsgSend.Name = "Txtmsgsend";
This.txtMsgSend.Size = new System.Drawing.Size (384, 21);
This.txtMsgSend.TabIndex = 4;
This.txtMsgSend.Text = "";
//
Button1
//
This.button1.Location = new System.Drawing.Point (408, 240);
This.button1.Name = "Button1";
This.button1.TabIndex = 5;
This.button1.Text = "Send";
This.button1.Click + = new System.EventHandler (this. Send_click);
//
Btnend
//
This.btnEnd.Location = new System.Drawing.Point (112, 16);
This.btnEnd.Name = "Btnend";
This.btnEnd.TabIndex = 6;
This.btnEnd.Text = "End";
This.btnEnd.Click + = new System.EventHandler (This.btnend_click);
//
Btnclose
//
This.btnClose.Location = new System.Drawing.Point (208, 16);
This.btnClose.Name = "Btnclose";
This.btnClose.TabIndex = 7;
This.btnClose.Text = "Close";
This.btnClose.Click + = new System.EventHandler (This.btnclose_click);
//
Form1
//
This. AutoScaleBaseSize = new System.Drawing.Size (6, 14);
This. ClientSize = new System.Drawing.Size (504, 273);
This. Controls.Add (This.btnclose);
This. Controls.Add (This.btnend);
This. Controls.Add (This.button1);
This. Controls.Add (This.txtmsgsend);
This. Controls.Add (This.txtmessagemain);
This. Controls.Add (This.txtserverip);
This. Controls.Add (This.btnjoin);
This. Controls.Add (This.btnstart);
This. Name = "Form1";
This. Text = "Udpwintest";
This. ResumeLayout (FALSE);

}
#endregion

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

private void btnStart_Click (object sender, System.EventArgs e)
{
LocalPort = Senderport;
RemotePort = Listenerport;

M_szhostname = Dns.gethostname ();
M_localhost = Dns.gethostbyname (m_szhostname);

Addtomain ("Local Port:" + LocalPort + ", Remote:" + remoteport);
Addtomain ("Initializing ...");

String localhostip = M_localhost.addresslist[0]. ToString ();
string[] Arrip = localhostip.split (New char[]{'. '});
Localhostip = "224" + "+" + arrip[1] + "." + arrip[2] + "." + arrip[3];

Initialize (Localhostip);

Addtomain ("Starting Listener thread ...");

Start a new thread
t = new Thread (new ThreadStart (Listener)); Listening for threads
T.start ();

this.btnJoin.Enabled = false;
this.btnStart.Enabled = false;

}

private void Btnjoin_click (object sender, System.EventArgs e)
{
LocalPort = Senderport;
RemotePort = Listenerport;

M_szhostname = Dns.gethostname ();
M_localhost = Dns.gethostbyname (m_szhostname);

Addtomain ("Local Port:" + LocalPort + ", Remote:" + remoteport);
Addtomain ("Initializing ...");

string ServerIP = This.txtServerIP.Text;
string[] Arrip = serverip.split (New char[]{'. '});
ServerIP = "224" + "+" + arrip[1] + "." + arrip[2] + "." + arrip[3];

Initialize (ServerIP);

Addtomain ("Starting Listener thread ...");

Start a new thread
t = new Thread (new ThreadStart (Listener)); Listening for threads
T.start ();

this.btnStart.Enabled = false;
this.btnJoin.Enabled = false;
}

private void Send_click (object sender, System.EventArgs e)
{
Start a new thread
t2 = new Thread (new ThreadStart (Send)); Listening for threads
T2. Start ();
}

<summary>
///
</summary>
public void Send ()
{
Thread.Sleep (1000);

Byte [] buffer = NULL;

System.Text.Encoding ASCII = System.Text.Encoding.ASCII;

String s = this.txtMsgSend.Text;

if (s.length = 0)
return;

if (String.Compare (s,0, "@", 0,1,true,cultureinfo.invariantculture) = = 0)
{
M_done = true;
s = m_szhostname + ": @";
Application.exit ();
}
Else
{
s = m_szhostname + ":" + S;
}


Buffer = new Byte[s.length + 1];

int len = ASCII. GetBytes (S.tochararray (), 0, s.length, buffer, 0);

int ecode = m_client.send (buffer, Len, m_remoteep);

if (ecode <= 0)
{
Addtomain ("Error in Send:" + Ecode);
}

T2. Abort ();

}

public static void Terminate ()
{
M_client.dropmulticastgroup (m_groupaddress);
}

<summary>
Class
</summary>
public void Initialize (string IP)
{

M_client = new UdpClient (localport);

Set the network address of a broadcast group
m_groupaddress = Ipaddress.parse (IP);

Try
{//Join Broadcast Group
M_client.joinmulticastgroup (m_groupaddress, 100);
}
catch (Exception ex)
{
string mm = ex. message;
Addtomain ("Unable to join multicast group" + Ex.) message);
}

Set Network Endpoint
M_remoteep = new IPEndPoint (m_groupaddress, RemotePort);

}

<summary>
///
</summary>
public void Listener ()
{

Thread.Sleep (2000);

System.Text.Encoding ASCII = System.Text.Encoding.ASCII;


while (!m_done)
{
IPEndPoint endpoint = null;
byte[] data = m_client.receive (ref endpoint);

String strdata = ASCII. GetString (data);

if (Strdata.indexof (": @") > 0)
{
Char [] separators = {': '};
String [] VARs = Strdata.split (separators);

if (vars[0] = = m_szhostname)//main system is off
{
Addtomain ("Shutting down Listener thread ...");
M_done = true;
}
Else
{
Addtomain (Vars[0] + "has left the conversation");
}
}
Else
{
if (Strdata.indexof (":") > 0)
{
Char [] separators = {': '};
String [] VARs = Strdata.split (separators);

if (Vars[0]!= m_szhostname)
{
Addtomain (strdata);
}
Else
{
Addtomain (strdata);
}
}
}
}
T.abort ();

Addtomain ("Listener thread finished ...");
Return
}

private void Addtomain (string _message)
{
This.txtMessageMain.Text = this.txtMessageMain.Text + _message + "\ r \ n";
}

private void Btnend_click (object sender, System.EventArgs e)
{
This.btnStart.Enabled = true;
This.btnJoin.Enabled = true;

Try
{
T.abort ();
T.interrupt ();
T2. Abort ();
T2. Interrupt ();

Addtomain ("Closing connection ...");

M_client.dropmulticastgroup (m_groupaddress);
}
Catch
{}


Terminate ();
}

private void btnClose_Click (object sender, System.EventArgs e)
{
Try
{
T.abort ();
T.interrupt ();
T2. Abort ();
T2. Interrupt ();
Terminate ();
}
Catch
{}
Application.exit ();
}
}
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.