asp.net C#使用UdpClient监听端口代码

作者:袖梨 2022-06-25

1.服务器端

 代码如下 复制代码

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //监听10086端口
            Server(10086);
        }

        ///


        /// 服务器端
        ///

        ///
        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); //停在这等待数据
                    string data = Encoding.Default.GetString(bytes, 0, bytes.Length);
                    udpclient.Close();

                    Console.WriteLine("{0:HH:mm:ss}从{1}发来数据:{2}", DateTime.Now, ipendpoint.Address, data);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, ex.Message);
            }
        }
    }
}

2.客户端

 代码如下 复制代码

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //发送数据
            Client("42.121.105.222", 10086, "mzwu.com");
        }

        ///


        /// 客户端
        ///

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

 

相关文章

精彩推荐