线程的应用udpClient通信

本文介绍了一个使用C#实现的简单UDP客户端和服务端通信的例子。通过创建两个线程分别用于发送和接收数据,演示了如何在本地计算机上进行UDP数据包的收发。此例涉及线程启动、数据编码及端口监听等关键技术点。
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();

            
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值