[C # network programming series] Topic 7: UDP programming supplement-Implementation of UDP broadcast programs

Source: Internet
Author: User

Due to the time relationship, I shared a question left over from the previous topic with you in this topic. This topic mainly introduces how to Implement UDP broadcast.Program, The following describes the implementation process andCodeAnd the running result.

I. Program Implementation

UDP broadcast program implementation code:

 

 Using  System;  Using  System. net;  Using  System. net. Sockets;  Using  System. text;  Using  System. Threading;  Using  System. Windows. forms;  Namespace  Udpbroadcast {  ///   <Summary>      /// On the interface, you can set the IP address and port number of the local process and add the address to a multicast group;  ///  You can enter the address of the target group for sending messages, and select the broadcast check box to send messages in broadcast mode.  ///  Click "accept" on the interface to start the receiving thread, so that the program can receive broadcast or multicast information.  ///   </Summary>      Public   Partial   Class  Udpbroadcasefrm: FORM {  Private  Udpclient sendudpclient;  Private  Udpclient receiveudpclient;  //  Multicast IP Address  Ipendpoint broadcastipendpoint;  Public  Udpbroadcasefrm () {initializecomponent (); IPaddress [] IPS = DNS. gethostaddresses (DNS. gethostname (); tbxlocalip. Text = IPS [ 5  ]. Tostring (); tbxlocalport. Text = "  8002  "  ;  //  Default group. The multicast address has a range.  //  For more information about multicast and broadcast, see UDP programming in my previous blog.  //  Local multicast group Tbxgroupip. Text = "  224.0.0.1  "  ;  //  Multicast Group sent Tbxsendtogroupip. Text = "  224.0.0.1 "  ;}  //  Set to join Group          Private   Void Chkbxjoingtoup_click ( Object  Sender, eventargs e ){  If (Chkbxjoingtoup. Checked = True  ) {Tbxgroupip. Enabled = False  ;}  Else  {Tbxgroupip. Enabled = True  ; Tbxgroupip. Focus ();}}  //  Set After Select sending Mode          Private  Void Chkbxbroadcast_click ( Object  Sender, eventargs e ){  If (Chkbxbroadcast. Checked = True  ) {Tbxsendtogroupip. Enabled = False  ;}  Else  {Tbxsendtogroupip. Enabled = True  ; Tbxsendtogroupip. Focus ();}}  //  Send message          Private   Void Btnsend_click ( Object  Sender, eventargs e ){ If (Tbxmessagesend. Text = ""  ) {MessageBox. Show (  "  Message content cannot be blank!  " , "  Prompt  "  );  Return  ;}  //  Send information according to the selected mode              If (Chkbxbroadcast. Checked = True  ){  //  Broadcast mode (automatically obtain the IP address broadcast address in the subnet) Broadcastipendpoint = New Ipendpoint (IPaddress. Broadcast, 8002 );}  Else  {  //  Multicast Mode Broadcastipendpoint = New Ipendpoint (IPaddress. parse (tbxsendtogroupip. Text ), 8002  );}  //  Start the sending thread to send messages Thread sendthread = New  Thread (sendmessage); sendthread. Start (tbxmessagesend. Text );}  //  Send message          Private   Void Sendmessage ( Object  OBJ ){  String Message =OBJ. tostring ();  Byte [] Messagebytes = Encoding. Unicode. getbytes (Message); sendudpclient = New  Udpclient ();  //  Send messages to multicast or broadcast addresses  Sendudpclient. Send (messagebytes, messagebytes. length, broadcastipendpoint); sendudpclient. Close ();  //  Clear edit message box  Resetmessagetext (tbxmessagesend );}  //  Use the delegate callback mechanism to clear messages on the Interface          Delegate   Void  Resetmessagetextcallback (textbox );  Private   Void Resetmessagetext (textbox ){  If  (Textbox. invokerequired) {resetmessagetextcallback resetmessagecallback = Resetmessagetext; textbox. Invoke (resetmessagecallback,  New   Object  [] {Textbox });}  Else  {Textbox. Clear (); textbox. Focus ();}}  //  Receive messages          Private   Void Btnreceive_click ( Object  Sender, eventargs e) {chkbxjoingtoup. Enabled = False ;  //  Create a receiving socket IPaddress localip = IPaddress. parse (tbxlocalip. Text); ipendpoint localipendpoint = New Ipendpoint (localip, Int  . Parse (tbxlocalport. Text); receiveudpclient = New  Udpclient (localipendpoint );  //  Add to multicast group              If (Chkbxjoingtoup. Checked = True  ) {Receiveudpclient. joinmulticastgroup (IPaddress. parse (tbxgroupip. Text); receiveudpclient. TTL = 50  ;} //  Start the receiving thread Thread threadreceive = New  Thread (receivemessage); threadreceive. Start ();}  //  Message Receiving Method          Private   Void  Receivemessage () {ipendpoint remoteipendpoint = New Ipendpoint (IPaddress. Any, 0  );  While ( True  ){  Try  {  //  An exception occurs when receiveudpclient is disabled.                      Byte [] Receivebytes = receiveudpclient. Receive ( Ref  Remoteipendpoint );  String Receivemessage = Encoding. Unicode. getstring (receivebytes );  //  Display message content Showmessage (lstmessagebox, String . Format ( "  {0} [{1}]  "  , Remoteipendpoint, receivemessage ));}  Catch  {  Break  ;}}}  //  Display the message content through the delegate callback mechanism          Delegate  Void Showmessagecallback (ListBox, String  Text );  Private   Void Showmessage (ListBox, String  Text ){  If  (ListBox. invokerequired) {showmessagecallback = Showmessage; ListBox. Invoke (showmessagecallback,  New   Object  [] {ListBox, text });}  Else  {ListBox. Items. Add (text); ListBox. selectedindex = ListBox. Items. Count- 1 ; ListBox. clearselected ();}}  //  Clear message list          Private   Void Btnclear_click ( Object  Sender, eventargs e) {lstmessagebox. Items. Clear ();}  //  Stop receiving          Private   Void Btnstop_click ( Object  Sender, eventargs e) {chkbxjoingtoup. Enabled = True  ; Receiveudpclient. Close ();}}} 

Broadcast demonstration result (the receiving thread is enabled after the receiving button is clicked directly at the receiving end, and the following interface is displayed after the "broadcast option" is selected on the sending end and the "send message" button is input ):

 

The following is the result of adding the receiver to the group. Terminate the receiving thread first, check the "add to group" check box, and then click "receive" to enable the receiving thread again. The output result is as follows:

The broadcast demonstration shows that the broadcast message is forwarded to all processes on the Internet at the same time. Whether the process is independent or is added to a multicast group, the broadcast message can be received.

The following shows the result of Multicast:

If you change the Group address of the receiving end to 224.0.0.3, the message "Multicast DEMO 2" sent by the sending end will not be sent to different multicast addresses, and the receiving end will not receive the message at this time.

From the multicast results, we can see that only processes with the multicast address 224.0.0.2 can receive information.

 

Note:It can be seen from the above: whether it is broadcast or multicast, the port number of the Process sent to it cannot be known only from the received information, therefore, both broadcast and multicast messages are sent anonymously. By understanding UDP broadcast and multicast, you can simply implement the function of sending a group of messages (this is the principle of chatting in QQ groups ).

 

Ii. Summary

This topic mainly serves as a supplement to the previous topic-Implementing a simple UDP broadcast (Multicast) program, this sending end can be sent to all users in the multicast address and all users in all subnets. This topic can be said to be an extension of UDP programming. I hope you can have a general understanding of UDP after reading this topic. In the next topic, I will introduce you to P2P programming.

All Source Code address: http://files.cnblogs.com/zhili/UDPBroadcast.zip

Related Article

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.