C # simple multicast example

Source: Internet
Author: User

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. net;
Using system. IO;
Using system. net. Sockets;
Using system. Threading;

Namespace consoleapplication1
{
Class Program
{
Static void main (string [] ARGs)
{
Multicastserver Server = new multicastserver ();
Multicastclient client = new multicastclient ();

Thread clientthread = new thread (New threadstart (client. receivedata ));
Clientthread. Start ();

Thread serverthread = new thread (New threadstart (server. senddata ));
Serverthread. Start ();

}
}

Class multicastserver {
Private IPaddress multicastip = IPaddress. parse ("224.110.10.1 ");
Private int Port = 5001;

Public void senddata ()
{
Console. writeline ("sender start ");
Ipendpoint multicastiep = new ipendpoint (multicastip, Port );
Udpclient sendudpclient = new udpclient ();

Sendudpclient. enablebroadcast = true;

String sendstring = "how are you ";
Byte [] bytes = system. Text. encoding. utf8.getbytes (sendstring );

Try
{
Sendudpclient. Send (bytes, bytes. length, multicastiep );
}
Catch
{
Console. writeline ("send error ");
}
Finally
{
Sendudpclient. Close ();
Console. writeline ("sender close ");
}
}
}

Class multicastclient {

Private IPaddress multicastip = IPaddress. parse ("224.110.10.1 ");
Private int Port = 5001;

Public void receivedata ()
{
Console. writeline ("reciever start ");
Udpclient receiveudp = new udpclient (this. Port );
Try
{
Receiveudp. joinmulticastgroup (this. multicastip, 10 );
}
Catch (socketexception E)
{
Console. writeline (E. Message. tostring ());
}

Ipendpoint remotehost = NULL;

While (true)
{
Try
{
Byte [] bytes = receiveudp. Receive (ref remotehost );
String STR = encoding. utf8.getstring (bytes, 0, bytes. Length );
Console. writeline (STR );
}
Catch
{
Console. writeline ("reciever close ");
Break;
}
}
}

}
}

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.