c#UDP通信实例复习

UDP服务器通信
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;


internal class Test
{
    private static Socket socket;
    private static Thread thread;
    public static void Main()
    {
        socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
        socket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788));
        thread = new Thread(show){IsBackground = true};
        thread.Start();
        Console.ReadKey();

    }

    public static void show()
    {
        while (true)
        {
            EndPoint remoteEndpoint = new IPEndPoint(IPAddress.Any, 0);
            Byte[] data = new byte[1024];
            int len = socket.ReceiveFrom(data, ref remoteEndpoint);
            string str = Encoding.UTF8.GetString(data, 0, len);
            Console.WriteLine(str);
            Console.WriteLine("地址;" + (remoteEndpoint as IPEndPoint).Address);
            Console.WriteLine("端口:" + (remoteEndpoint as IPEndPoint).Port);
        }
    }
}

UDP客户端通信
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

internal class Test
{
    public static void Main()
    {
        Socket socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
        while (true)
        {
            EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7788);
            string str = Console.ReadLine();
            Byte[] data = Encoding.UTF8.GetBytes(str);
            socket.SendTo(data, point);
        }
        
        Console.ReadKey();
    }
}


2.使用封装的类来实现

//创建主机
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

internal class Test
{
    public static void Main()
    {
        UdpClient udpclient=new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788));
        //创建UDPclient
        IPEndPoint point=new IPEndPoint(IPAddress.Any,0);
        Byte[] data = udpclient.Receive(ref point);  
        //接受数据和对方主机信息
        string str = Encoding.UTF8.GetString(data, 0, data.Length);
        Console.WriteLine(str);
    }
}

//创建客户端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

internal class Test
{
    public static void Main()
    {
        UdpClient client = new UdpClient();
        string str = Console.ReadLine();
        Byte[] data = Encoding.UTF8.GetBytes(str);
        //client.Send(data, data.Length,new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788));
        client.Send(data, data.Length, "127.0.0.1", 7788);
        Console.ReadLine();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值