线程的应用udpClient通信

来源:互联网 发布:开淘宝店需要多少钱 编辑:程序博客网 时间:2024/06/05 03:27
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace UDP
{
    class Program
    {
        private static  UdpClient udpSender;

        private static  UdpClient udpRecver;

        static void Main(string[] args)
        {
            //BeginListen();
            IPEndPoint localIpEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345); //本机ip,发送的ip地址

            udpSender = new UdpClient(localIpEP);


            Thread thrSend = new Thread(SendMessage);  发送的线程

            thrSend.Start("hello,this is server");

            BeginListen();     开启接收线程

            Console.WriteLine("server started");


            Console.Read();
        }
        private static void BeginListen()
        {
            IPEndPoint localIpep = new IPEndPoint(

           IPAddress.Parse("127.0.0.1"), 8849); // 本机IP和监听端口号 ********************这个监听端口是必须的(个人的理解)



            udpRecver = new UdpClient(localIpep);

            Thread thrReceive = new Thread(ReceiveMessage);

            thrReceive.Start();

            Console.WriteLine("client started");
        }
        private static void ReceiveMessage()
        {
            // throw new NotImplementedException();

            IPEndPoint remoteIpEP = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                // 从远处接收到的数据
                byte[] bytReceive = udpRecver.Receive(ref remoteIpEP);

                string msg = Encoding.Unicode.GetString(bytReceive, 0, bytReceive.Length);

                Console.WriteLine("received from server");
                Console.WriteLine(msg);
            }
            
        }

        private static void SendMessage(object obj)
        {
            //throw new NotImplementedException();

            // string msg = (string)obj;
            string msg ="this is send data";

            byte[] sendbytes = Encoding.Unicode.GetBytes(msg);
            //发送到的ip地址
            IPEndPoint remoteIpEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8849);  发送到的ip地址

            udpSender.Send(sendbytes, sendbytes.Length, remoteIpEP);

            udpSender.Close();

            
        }
    }
}

原创粉丝点击