asp.net C#使用UdpClient監聽連接埠代碼

來源:互聯網
上載者:User

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

        /// <summary>
        /// 伺服器端
        /// </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); //停在這等待資料
                    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");
        }

        /// <summary>
        /// 用戶端
        /// </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();
            }
        }
    }
}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.