UDP的应用

User Data Protocol 用户数据报协议

最大努力交付原则,只管发送,不管对象是否存在

(1)创建Socket对象:

 ip地址:IPAddress.Parse(strIP),字符串转换
 端口:port
 协议:UdpClient service

//ip
public string strIP;
//端口
public int port;

private void Start()
    {
        IPEndPoint locaIEP = new IPEndPoint(IPAddress.Parse(strIP),port);
        UdpClient  service = new UdpClient(locaIEP);

    }

(2)发送数据

获取传输对象(此为在同一物体下挂载的脚本获取方法): 

IPEndPoint remote = GetComponent<UdpReceiveDemo>().locaIEP;

传输对象的脚本

    //ip
    public string strIP;
    //端口
    public int port;
private void Start()
    {
        locaIEP = new IPEndPoint(IPAddress.Parse(strIP), port);
    }

service.Send(byte[]数组 , 数组长度 , 传输对象);

 //传输方法
 public void SendChatMessage(string msg)
    {
        byte[] data =  Encoding.UTF8.GetBytes(msg);
        IPEndPoint remote = GetComponent<UdpReceiveDemo>().locaIEP;
        int count = service.Send(data,data.Length,remote);
        //实际发送的字节数
        Debug.Log(count);
    }

(3)释放资源

 private void OnApplicationQuit()
    {
        service.Close();
    }

概述

UDP是不连接的数据报模式。即传输数据之前源端和终端不建立连接。使用尽最大努力交付原则,即不保证可靠交付。

数据报模式:由于不建立连接,收到的数据可能是任意主机发送的,所以接收端Read次数必须与发送端Write次数相同,每次只接收一个报文,避免多个报文合并。但如果报文过长,多出部分会被丢弃,所以注意数据最大为1472字节。

一,演示Unity3D基于UDP协议发送消息

命名空间:

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

1.发送信息脚本

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

/// <summary>
/// 基于UDP协议发送消息
/// </summary>
public class UdpSendDemo : MonoBehaviour 
{
    //ip
    public string strIP;
    //端口
    public int port;
    //成员变量
    private UdpClient service;

    public InputField msgInput;

    //1.创建Socket对象
    private void Start()
    {
        IPEndPoint locaIEP = new IPEndPoint(IPAddress.Parse(strIP),port);
        service = new UdpClient(locaIEP);


    }
    //2.发送消息方法
    public void SendChatMessage(string msg)
    {
        byte[] data =  Encoding.UTF8.GetBytes(msg);
         IPEndPoint remote = GetComponent<UdpReceiveDemo>().locaIEP;
        int count = service.Send(data,data.Length,remote);
        //实际发送的字节数
        Debug.Log(count);
    }
    //3.发送消息按钮事件处理方法
    public void OnSendButtonClick()
    {
        SendChatMessage(msgInput.text);
    }
    //4.释放资源
    private void OnApplicationQuit()
    {
        service.Close();
    }
}   

2.接收消息脚本,Receive方法在没有收到消息时,会阻塞线程,并且unityAPI无法在子线程调用,所以必须使用线程交叉访问助手

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

 /// <summary>
 /// 
 /// </summary>
public class UdpReceiveDemo : MonoBehaviour
{	 //ip
    public string strIP;
    //端口
    public int port;
    //成员变量
    [HideInInspector]
    public IPEndPoint locaIEP;
    private UdpClient service;

    public ChatView chat;
    private Thread threadReceive;
    //1.创建Socket对象
    private void Start()
    {
        locaIEP = new IPEndPoint(IPAddress.Parse(strIP), port);
        service = new UdpClient(locaIEP);
        threadReceive = new Thread(ReceiveChatMessage);
        threadReceive.Start();
    }

    //2.接收消息
    public void ReceiveChatMessage()
    {
        while (true)
        {
            //ref 引用参数:改变数据
            //传递可以接收的终结点,如果接收到则修改为实际终结点。通常传递任意终结点
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
            //Receive方法在没有收到消息时,会阻塞线程
            byte[] data = service.Receive(ref remote);
            Debug.Log("收到");
            string msg = Encoding.UTF8.GetString(data);

            DisplayMessage(msg);
        }
    }

    //3.显示数据
    private void DisplayMessage(string msg)
    {
        ThreadCrossHelper.Instance.ExecuteOnMainThread(() => 
        {
            chat.DataSource.Add(new ChatLine()
            {
                UserName = "QTX",
                Message = msg,
                Time = DateTime.Now,
                Type = ChatLineType.User,
            });
        });
    }

    //4.释放资源
    private void OnApplicationQuit()
    {
        threadReceive.Abort();
        service.Close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值