Use UDP broadcast mode to write simple information transmission tools ~

xiaoxiao2021-03-06  56

Original: http://ms.mblogger.cn/minBear/posts/1977.aspx

Use UDP broadcast mode to write simple information transmission tools ~

// Use udpclient class // this is my test code for the reference ~ // Author: minbear // Date: 2004-2-29

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; use system.text; Namespace UDPWINTEST {///

/// Form1 summary description. /// 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; /// // / / The designer variable. /// 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 () {INITIALIZECMOMPONENT ();} /// /// Clean all the resources being used.

/// Protected Override Void Dispose (Bool Disposing) {if (disponents! = null) {Components.dispose ();}} Base.Dispose (DISPOSION);} #Region Windows Form The code generated by the designer ///

/// designer supports the required method - do not use the code editor to modify the // / this method.

/// 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.butt On1.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.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 ///

/// The primary point of the application.

/// [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 ("Starting Listener Thread ..."); // Start the new thread (New ThreadStart (Listener)); // Listening Thread T.Start (); this.btnjoin.enabled = false; this.btnStart.enabled = f alse;} 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; "Starting Listener Thread ..."); // Start the new thread T = new thread (new threadstart (listner)); // listens on thread T.Start (); this.btnStart.enabled = false; this.btnjoin.enabled = false;} private void send_click (Object Sender, system.eventargs e) {// Start New Thread T2 = New ThreadStart (Send)); // Listening Thread T2.Start ();} ///

/// /// < / 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);} ///

/// initialization /// public void Initialize (string IP) {m_Client = new UdpClient (LocalPort); / / Set the network address m_groupaddress = ipaddress.parse (ip); try {// joining broadcast group m_client.joinMulticastGroup (m_groupaddress, 100);} catch (exception ex) {string mm = ex. measure; addTomain ("Unable) To join multicast group " ex. amount);} // set network endpoint m_remoteep = new ipndpoint (m_groupaddress, remotEport);} /// /// /// public void listener () { Thread.Sleep (2000); System.Text.Encoding ASCII = System.Text.Encoding.ascii; While (! M_done) {ipen DPOINT 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) // The main system is turned 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}}}}};}}}} T.abort (); AddTomain 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.ENABED = true; try {t.abort (); t.interrupt (); t2.abort (); t2.interrupt (); addtomain ("Closing Connection ..."); m_client.dropmultativeGroup (m_groupaddress );} CatCh {} // terminate ();} private void btnclose_click (object sender, system.eventargs e) {TRY {T.abort (); T.InterRupt (); t2.abort (); t2.interrupt ( Terminate ();

转载请注明原文地址:https://www.9cbs.com/read-114855.html

New Post(0)