C# UDP网络通讯

来自我的阿里云 外网IP为39.106.215.68       需要在阿里云里开放一个你需要的端口,最好把入口和出口都设置一下并弄成一样的,我的开放端口为8899

      服务端代码(采用控制台应用程序)  
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

namespace ConsoleApplication1
{
    class Program
    {
        static Socket m_udp_server;

        static IPEndPoint client_endpoint;

        static byte[] bt = new byte[1024];

        static string str = "";

        static EndPoint client_ip_port;

        static int port = 8899;

        static void Main(string[] args)
        {
            try
            {
                m_udp_server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//实例化socket
                IPEndPoint server_endpoint = new IPEndPoint(IPAddress.Any, 8899);
                m_udp_server.Bind(server_endpoint);//Socket对象跟服务器端的IP和端口绑定

               // client_endpoint =  server_endpoint;//接收任何客户端和任何端口
               client_ip_port = (EndPoint)server_endpoint;//实例化客户端 


                //开始异步接收消息  接收后,client_ip_port存储的是客户端的IP和端口
                m_udp_server.BeginReceiveFrom(bt, 0, bt.Length, 0, ref client_ip_port, new AsyncCallback(Receive), client_ip_port);

               
            }catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.WriteLine("UDP服务端开始监听...");
            Console.ReadLine();

            
        }


        static void Receive(IAsyncResult iar)
        {
            try
            {    
                //结束异步接收消息  len表示接收到的字符数
                int len = m_udp_server.EndReceiveFrom(iar, ref client_ip_port);
                var iep = (IPEndPoint)client_ip_port;

                if (len <= 0) return;
                str = Encoding.UTF8.GetString(bt, 0, len);
                
                Console.WriteLine(DateTime.Now.ToString() + "  " + iep.Address + ":" + iep.Port + " 接收到的数据为 " + str);

                // 将字符串消息转为数组
                byte[] bytes = Encoding.UTF8.GetBytes(str);

                //异步给客户端发送消息
                Send(m_udp_server, client_ip_port, iep.Address + ":" + iep.Port +"说:" + "你的消息我收到了");


                //重新实例化接收数据字节数组
                bt = new byte[1024];
                //开始继续异步接收消息 
                m_udp_server.BeginReceiveFrom(bt, 0, bt.Length, 0, ref client_ip_port, new AsyncCallback(Receive), client_ip_port);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }




        static void Send(Socket client, EndPoint ep, string str)
        {
            // 将字符串消息转为数组
            byte[] bytes = Encoding.UTF8.GetBytes(str);

            //开始异步发送消息  ep是上次接收消息时的客户端IP和端口信息
            client.BeginSendTo(bytes, 0, bytes.Length, SocketFlags.None, ep, new AsyncCallback(SendData), ep);
        }


        static void SendData(IAsyncResult iar)
        {
            Console.WriteLine("给客户端发送消息完毕.");
            m_udp_server.EndSend(iar);
        }

    }
}

 

 

 

 

客户端代码(使用的winform)

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;
using System.Net.Sockets;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        string host = "39.106.215.68"; //为我的阿里云外网IP
        int port = 8899;

        //客户端 Socket对象
        Socket m_udp_client1;

        //服务器端 终点
        EndPoint epServer;

        //接收数据的字符数组
        byte[] receiveData;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //客户端Socket对象实例化
                m_udp_client1 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                //设置服务器端IP地址和对应端口
                IPEndPoint server = new IPEndPoint(IPAddress.Parse(host), port);
                //实例化服务器端 终点
                epServer = (EndPoint)server;

                //开启异步接收服务端的信息
                receiveData = new byte[1024];
                m_udp_client1.BeginReceiveFrom(receiveData, 0, receiveData.Length, SocketFlags.None, ref epServer, new AsyncCallback(ReceiveData), null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        //异步接收消息结束
        void ReceiveData(IAsyncResult iar)
        {
            //完成异步接收  recv 表示接收到的字节数
            int recv = m_udp_client1.EndReceive(iar);
            //将接收到的数据打印出来
            Console.WriteLine("Server: " + Encoding.UTF8.GetString(receiveData, 0, recv));
        }

       



        //点击按钮开始像服务端异步发送消息
        string str = "";
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //向服务端异步发送消息
                str = "哈哈哈111";
                byte[] sendData = Encoding.UTF8.GetBytes(str);
                //参数:sendData           要发送的数据
                //参数:0:                 要发送数据的起始位置
                //参数:sendData.Length:   要发送数据的字节数
                //参数:SocketFlags.None:  按位组合方式
                //参数:epServer:          接收方设备(包含IP和端口)
                //参数:new AsyncCallback(SendData):   委托
                //参数:null:          请求的状态信息
                m_udp_client1.BeginSendTo(sendData, 0, sendData.Length, SocketFlags.None, epServer, new AsyncCallback(SendData), null);

                //开启异步接收服务端的信息
                receiveData = new byte[1024];
                m_udp_client1.BeginReceiveFrom(receiveData, 0, receiveData.Length, SocketFlags.None, ref epServer, new AsyncCallback(ReceiveData), null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex);
            }
        }

        //异步发送消息结束
        void SendData(IAsyncResult iar)
        {
            //完成异步发送
            m_udp_client1.EndSend(iar);
        }


        //点击关闭窗口才会调用
        private void m_closing(object sender, FormClosingEventArgs e)
        {
            //Console.WriteLine("关闭了");
            if (m_udp_client1 != null)
            {
                m_udp_client1.Close();
                m_udp_client1 = null;
                receiveData = null;
                epServer = null;
            }
        }
    }
}

 

这个打包出来可以使用(客户端代码可以多台机器用,相当于很多的客户端)亲测

你可能感兴趣的:(Unity)