卜若的代码笔记-protobuf系列-第三章:Protobuf在Unity的使用

3.1 请参考下面的文章

参考文章

看完这篇文章你基本就能够在客户端使用protobuf

3.2 使用UDP协议发送byte流

使用的protobuf模型:

syntax = "proto3"; // proto协议版本
message Player{
   int32 id = 1;//同上
   int32 hp = 2;//必须字段,在后面的使用中必须为该段设置值
   int32 skill = 3;//可选字段,在后面的使用中可以自由决定是否为该字段设置值
}  

客户端代码:

using Google.Protobuf;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class Client : MonoBehaviour
{

    private IPEndPoint point;
    private UdpClient client;
    int rd;
    
    bool endClient { get; set; }
    public string IP { get; set; }

    void Awake()
    {
        rd = UnityEngine.Random.Range(0, 30000);//随机绑定端口,支持多开
    }
    private void Start()
    {

        begin();
    }

    public void begin()
    {



        if (client == null)
        {

            IP = "127.0.0.1";
            //重新填写ip,
            point = new IPEndPoint(IPAddress.Parse(IP), 9002);
            client = new UdpClient(new IPEndPoint(IPAddress.Any, rd + 10000));
            client.Connect(point);

            Player reqMsg = new Player();
            reqMsg.Id = 33;
            reqMsg.Hp = 100;
            reqMsg.Skill = 191;
            byte[] datas = reqMsg.ToByteArray(); // 把对象转换为字节数组

            client.Send(datas, datas.Length);//发送数据



        }



    }


 
    private void OnApplicationQuit()
    { 
        endClient = true;
        if (client == null)
            return;
        
        client.Close();
    }
  
}

接收代码:

结果显示:

数据正确:非常完美

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值