上篇介绍了关于网络工具的帧调用API的注册监听实现,本篇真正介绍如何使用前面编写的网络工具实现向服务器发送消息,以及监听服务器返回的消息。
测试脚本如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using W.NetWork;
using MyGame.Sample;
using FlatBuffers;
/*
* Author:W
* 网络通信测试
* 1.模拟向服务器发送消息
* 2.监听服务器返回的消息
*/
public class Test : MonoBehaviour {
// Use this for initialization
void Start () {
NetHelper.Instance.AddMsgListener(10001, OnServerMsgCallBack);
}
void OnDestroy()
{
if(NetHelper.Instance!=null)
NetHelper.Instance.RemoveMsgListener(10001);
}
/// <summary>
/// 服务器10001消息监听处理
/// </summary>
/// <param name="value"></param>
private void OnServerMsgCallBack(byte[] value)
{
Weapon weapon = Weapon.GetRootAsWeapon(new ByteBuffer(value));
Debug.Log(" 10001 服务器消息解析处理: weapn name="+weapon.Name+" damage="+weapon.Damage);
}
/// <summary>
/// 模拟向服务器发送一条消息
/// </summary>
private void SendWeaponMsgInfo()
{
var builder = new FlatBufferBuilder(512);
var name = builder.CreateString("Sowrd");
Weapon.StartWeapon(builder);
Weapon.AddName(builder,name);
Weapon.AddDamage(builder,(short)25);
var weapon = Weapon.EndWeapon(builder);
builder.Finish(weapon.Value);
byte[] buf = builder.SizedByteArray();
NetHelper.Instance.SendMsgToServer(10001,buf);
builder.Clear();
}
// Update is called once per frame
void Update () {
}
}
至此,关于Socket与FlatBuffer协议实现的网络实时同步,客户端的工具编写完成。文章最后提供Demo工程链接:https://pan.baidu.com/s/1BqGAB0NYVg4GufDnFuvO9w 提取码:ahv8