unity基于UDP协议通信(完善之前的)

工具:unity2019.2.6f1、vs2019

一、使用VS2019创建UDP服务器

代码如下:

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

namespace UDP服务器
{
    class Program
    {
        private static Socket server;
        private static IPAddress ip;
        private static EndPoint ep;

        private static IPEndPoint clientIP;

        static void Main(string[] args)
        {
            createServer();

            Thread t = new Thread(new ThreadStart(() => {
                receiveMessageFromClient();
            }));
            t.Start();

            Thread t1 = new Thread(new ThreadStart(() => { sendTest(); }));
            t1.Start();

            Console.Read();
        }

        private static void createServer()
        {
            //创建udp服务器并绑定ip 端口号
             server = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);

             ip = IPAddress.Parse("192.168.11.117");
             ep = new IPEndPoint(ip,12345);

            server.Bind(ep);
        }

        /// <summary>
        /// 给客户端发消息 收到客户端消息后回发
        /// </summary>
        public static void sendMessageToClient() 
        {
            string m = "我是服务器,接收到你发来的消息";
            byte[] data= Encoding.UTF8.GetBytes(m);

            UdpClient client = new UdpClient();
            client.Send(data,data.Length,clientIP);// 客户端的ip 端口
        }

        /// <summary>
        /// 输入信息发送消息 (ip地址与端口号确定的情况)
        /// </summary>
        public static void sendTest() 
        {
            while (true) 
            {
                string mes = Console.ReadLine();
                
                byte[] data = Encoding.UTF8.GetBytes(mes);

                UdpClient client = new UdpClient();

                IPEndPoint p = new IPEndPoint(IPAddress.Parse("192.168.11.117"), 60000);

                client.Send(data, data.Length, p);
            }
        }

        /// <summary>
        /// 接收客户端发送的消息
        /// </summary>
        public static void receiveMessageFromClient() 
        {
            Console.WriteLine("服务器启动。。。。");

            string message;
            byte[] datas = new byte[1024];
         
            while (true) 
            {
                try 
                {
                    server.ReceiveFrom(datas,ref ep);
                    clientIP =(IPEndPoint)ep;
                    message = Encoding.UTF8.GetString(datas);

                    Console.WriteLine("接收到客户端"+ (ep  as IPEndPoint).Address+ "的消息:"+message);
                    sendMessageToClient();//回发消息

                }
                catch (Exception e) 
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
}

二 、使用unity2019创建UDP客户端

代码如下:

using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
using UnityEngine.UI;
using System.Text;
using System;
using System.Threading;

public class UDPClient : MonoBehaviour
{
    private IPAddress ip;
    private IPEndPoint ep;

    public Transform mesText;
    private string mes;

    //test
    UdpClient client;

    void Start()
    {
        client = new UdpClient(60000, AddressFamily.InterNetwork);
        createClient();

        Thread t = new Thread(new ThreadStart(() => { receiveMessageFromServer(); }));
        t.Start();
    }

    private void Update()

    {
        mesText.GetComponent<Text>().text = mes;
    }

    private void createClient()
    {
       // client = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); 

        // 服务器ip和端口号
        ip = IPAddress.Parse("192.168.11.117");
        ep =new IPEndPoint(ip, 12345);
    }

    /// <summary>
    /// 给服务器发消息 点击按钮发送
    /// </summary>
    public void sendMessageToServer() 
    {
       string message = "hello";
       byte[] datas=  Encoding.UTF8.GetBytes(message);

        client.Send(datas,datas.Length,ep);
    }


    /// <summary>
    /// 从服务器接收消息 放在携程或者线程里处理
    /// </summary>
    private void receiveMessageFromServer() 
    {
        byte[] datas = new byte[1024];

        IPEndPoint ep1 = ep;
        while (true) 
        {
            EndPoint remote = (ep as EndPoint);
       
            datas=client.Receive(ref ep1);

            string message = Encoding.UTF8.GetString(datas);

            mes += message+"\n";
        }
    }
}

三、 运行测试

服务器运行结果:

客户端运行结果:

四 、完善说明

该事例包含客户端通过按钮发送消息给服务器、客户端通过线程实时接收服务器发来的消息、服务器实时接收客户端发来的消息并得到该客户端的IP地址和端口号加以回复消息、服务器还可单独向某一个客户端发送消息(前提知道知道客户端的IP地址和端口号)

 

注:因为代码全部粘上去了,demo就不上传了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值