Asp.net C # use UdpClient to listen to port code

Source: Internet
Author: User

1. Server-side

The code is as follows Copy Code

Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;

Namespace ConsoleApplication1
{
Class Program
{
static void Main (string[] args)
{
Listening on port 10086.
Server (10086);
}

<summary>
Server-side
</summary>
<param name= "Port" ></param>
static void Server (int port)
{
Try
{
while (true)
{
UdpClient udpclient = new UdpClient (port);
IPEndPoint IPEndPoint = new IPEndPoint (Ipaddress.any, Port);
byte[] bytes = UdpClient. Receive (ref IPEndPoint); Stop here waiting for the data
String data = Encoding.Default.GetString (bytes, 0, bytes. Length);
UdpClient. Close ();

Console.WriteLine ("{0:HH:MM:SS}" sends data from {1}: {2} ", DateTime.Now, IPEndPoint. address, data);
}
}
catch (Exception ex)
{
Console.WriteLine ("{0:hh:mm:ss}->{1}", DateTime.Now, ex.) message);
}
}
}
}

2. Client

The code is as follows Copy Code

Using System;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;

Namespace ConsoleApplication1
{
Class Program
{
static void Main (string[] args)
{
Send data
Client ("42.121.105.222", 10086, "mzwu.com");
}

<summary>
Client
</summary>
<param name= "IP" ></param>
<param name= "Port" ></param>
<param name= "Message" ></param>
static void Client (string ip, int port, string message)
{
Try
{
Socket socket = new socket (addressfamily.internetwork, Sockettype.dgram, PROTOCOLTYPE.UDP);
IPEndPoint IPEndPoint = new IPEndPoint (Ipaddress.parse (IP), port);
byte[] data = Encoding.Default.GetBytes (message);
Socket. SendTo (data, IPEndPoint);
Socket. Close ();
}
catch (Exception ex)
{
Console.WriteLine ("{0:hh:mm:ss}->{1}", DateTime.Now, ex.) message);
Console.readkey ();
}
}
}
}

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.