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;
using System.Windows.Forms;

namespace TestConsoleUDP.MySocket
{
    public class UdpReceive
    {
        #region 服务端1
        private static Socket udpServer;
        public static void startUdpReceive()
        {
            Console.WriteLine("------startUdpReceive--");
            udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.3.34"), 18083));
            new Thread(ReceiveMessage)
            {
                IsBackground = true
            }.Start();
        }

        // 使用UdpClient类来写接收端
        private static void ReceiveMessage()
        {
            Console.WriteLine("------ReceiveMessage--");
            while (true)
            {
                byte[] data = new byte[10240];
                EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
                int count = udpServer.ReceiveFrom(data, ref endPoint);
                if (count > 0)
                {
                    string message = Encoding.UTF8.GetString(data, 0, count);
                    Console.WriteLine
                        ("-----从ip" + (endPoint as IPEndPoint).Address.ToString()
                        + ":" + (endPoint as IPEndPoint).Port + "Get" + message);
                }

            }
        }
        #endregion

        #region 服务端2
        static UdpClient udpcRecv;
        public static void UdpServices()
        {
            try
            {
                IPAddress ip = IPAddress.Parse("192.168.100.123");//192.168.3.34
                IPEndPoint remoteIpep = new IPEndPoint(ip, 65505);//18083
                udpcRecv = new UdpClient(remoteIpep);
                Thread thrRecv = new Thread(ReceiveMessage22);
                thrRecv.IsBackground = true;
                thrRecv.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误", "请检查网络 "+ex.Message);
            }
        }

        private static void ReceiveMessage22()
        {
            IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0);
            Console.WriteLine("-----remoteIpep:" + remoteIpep.Address + ":" + remoteIpep.Port);
            while (true)
            {
                try
                {
                    byte[] bytRecv = udpcRecv.Receive(ref remoteIpep);
                    string message = StringToHexString(bytRecv, bytRecv.Length);
                    string strInfo = DateTime.Now.ToString() + " receive[" + remoteIpep.Address + ":" + remoteIpep.Port + "]: " + message;
                    Console.WriteLine(strInfo);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("UDP异常", ex.Message);
                }
            }
        }

        private static string StringToHexString(byte[] b, int len)
        {
            string result = string.Empty;
            for (int i = 0; i < len; i++)//逐字节变为16进制字符
            {
                result += Convert.ToString(b[i], 16);
                if (i < b.Length - 1)
                    result += " ";
            }
            return result;
        }
        #endregion

        #region 发送端
        public static void SendMsg()
        {
            UdpClient udpClient = new UdpClient();
            try
            {
                udpClient.Connect("192.168.100.100", 65505);//"192.168.3.34", 64505
                Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there");
                while (true)
                {
                    udpClient.Send(sendBytes, sendBytes.Length);
                    string strInfo = DateTime.Now.ToString() + " send[192.168.100.100:65505]: Is anybody there" ;
                    Console.WriteLine(strInfo);
                    Thread.Sleep(3000);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        #endregion
    }
}

测试UDP收发消息:

using System;
using TestConsoleUDP.MySocket;

namespace TestConsoleUDP
{
    class Program
    {
        private static TestSocketServer socketServer = new TestSocketServer();
        private static UDPServer server = new UDPServer();

        static void Main(string[] args)
        {
            UdpReceive.UdpServices();
            UdpReceive.SendMsg();

            Console.ReadLine();
        }

    }
}


 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值