. Net simple broadcast implementation

Source: Internet
Author: User
Code

Class Program
{

Static bool connecting = true;
Static void main ()
{
Received ();
While (connecting)
{
String content = console. Readline ();
If (content. length> 0)
{
If (string. Compare (content, "<Stop>", true) = 0)
{
Console. writeline ("close ...");
Connecting = false;
}
Else
{
Send (content );
}
}
}
Console. readkey ();
}

Public static void send (string content)
{
Socket sock = new socket (addressfamily. InterNetwork, sockettype. dgram, protocoltype. UDP );
// Ipendpoint iep1 = new ipendpoint (IPaddress. Broadcast, 9050); // 255.255.255.255
Ipendpoint iep2 = new ipendpoint (IPaddress. parse ("192.168.100.255"), 9050 );
// String hostname = DNS. gethostname ();
Byte [] DATA = encoding. ASCII. getbytes (content );
Sock. setsocketoption (socketoptionlevel. socket,
Socketoptionname. Broadcast, 1 );
// Sock. sendto (data, iep1 );
Sock. sendto (data, iep2 );
Sock. Close ();
}

Public static void received ()
{
Threadpool. queueuserworkitem (x) =>
{
Socket sock = new socket (addressfamily. InterNetwork, sockettype. dgram, protocoltype. UDP );
Ipendpoint IEP = new ipendpoint (IPaddress. Any, 9050 );
Sock. BIND (IEP );
Endpoint Ep = (endpoint) IEP;

Byte [] data;
Int Recv;
String stringdata;
Console. writeline ("enable answering ...");
While (connecting)
{
Data = new byte [2, 1024];
Recv = sock. receivefrom (data, ref EP );
Stringdata = encoding. ASCII. getstring (data, 0, Recv );
Console. writeline ("information: {0} from: {1}", stringdata, ep. tostring ());
}
Console. writeline ("Answer closed ...");
Sock. Close ();
});
}

}

 

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.