一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2022-06-25 08:13:31 编辑:袖梨 来源:一聚教程网

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

 

热门栏目