C# 使用udp实现消息的接收和发送

代码比较简单,但是别忘记关闭防火墙进行测试

首先便是服务端,使用Socket进行实现,参考代码如下:

        private static Socket udpServer;
        static void startUdpReceive()
        {
            Console.WriteLine("------startUdpReceive--");
            udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.106"), 10023));
            new Thread(ReceiveMessage)
            {
                IsBackground = true
            }.Start();
        }

        private static void ReceiveMessage()
        {
            Console.WriteLine("------ReceiveMessage--");
            while (true)
            {
                byte[] data = new byte[1024];
                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);
                }

            }
        }

在绑定socket端口的时候,需要提供绑定的ip和端口号,如这里是

udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.106"), 10023));

本机ip是是192.168.2.106,绑定端口是10023。然后使用while循环监听消息。对于本机来说,也可以使用 udpServer.Bind(new IPEndPoint(IPAddress.Any, 10023)); 只绑定端口,对于ip则不限制。

也可以不用Socket而是直接使用UdpClient类来写接收端,效果类似:

        static UdpClient udpcRecv;
        public static void UdpServices()
        {
            try
            {
                IPAddress ip = IPAddress.Parse("192.168.2.106");
                IPEndPoint remoteIpep = new IPEndPoint(ip, 10023);
                udpcRecv = new UdpClient(remoteIpep);
                Thread thrRecv = new Thread(ReceiveMessage22);
                thrRecv.IsBackground = true;
                thrRecv.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误", "请检查网络");
            }

        }


        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 = Encoding.UTF8.GetString(
                        bytRecv, 0, bytRecv.Length);
                    Console.WriteLine("-----reveice  message:" + message);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("UDP异常", ex.Message);
                }
            }
        }

接下来是发送端:

            UdpClient udpClient = new UdpClient();
            try
            {
                udpClient.Connect("192.168.2.106", 10023);
                Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there??????");
                udpClient.Send(sendBytes, sendBytes.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

如果代码爆红则应该是导包的问题,加入以下即可。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;
using System.Management;
using System.Threading;

上面都写好后可以测试了,但是我却遇到了问题,后面才知道是电脑端防火墙没开导致,所以和电脑端调试网络通信的时候,需要关闭防火墙,才能收到数据。

你可能感兴趣的:(android,c#,udp)