unity学习(23)——客户端与服务器合力完成注册功能(5)客户端显示注册结果

注册过程最后一步,有这个基础,登录也非常简单了。

cs 复制代码
session.write(0, 0, 3, (object)new BoolDTO(v));

直接进write函数,很明显就是给客户端返回一个数据包。

cs 复制代码
 public void write(int type, int area, int command, object message)
 {
   SocketModel socketModel = new SocketModel(type, area, command, (string) null);
   if (message != null)
     socketModel.Message = Coding<object>.encode(message);
   int num1 = 16;
   if (socketModel.Message != null)
     num1 += socketModel.Message.Length;
   ByteArray byteArray = new ByteArray();
   byteArray.WriteInt(num1);
   byteArray.WriteInt(socketModel.Type);
   byteArray.WriteInt(socketModel.Area);
   byteArray.WriteInt(socketModel.Command);
   if (socketModel.Message != null)
   {
     int num2 = num1 + socketModel.Message.Length;
     byteArray.WriteInt(socketModel.Message.Length);
     byteArray.WriteUTFBytes(socketModel.Message);
   }
   else
     byteArray.WriteInt(0);
   this.socket.Send(byteArray.Buffer);
   Console.WriteLine("session.write返回给客户端的消息长度" + (object)byteArray.Buffer.Length);
         //MyLog.form.textAdd("消息长度" + (object) byteArray.Buffer.Length);
 }

服务器的过程

现在要去客户端那边读取这条消息。通过.sln打开服务器项目。客户端在初始化的时候就已经建立了socket,接受回调函数的内容如下,接受信息的作用。

cs 复制代码
 private static void ReceiveCallBack( IAsyncResult ar)//回调方法 
 {
     try
     {
         int readCount = 0;
         readCount = socket.EndReceive(ar);//ar其实就是传进来的内容
         byte[] temp = new byte[readCount];
         Buffer.BlockCopy(buff, 0, temp, 0, readCount);
         Debug.Log("小丑到底是谁:"+readCount);
         Debug.Log("ReceiveCallBack里的buff:" + BitConverter.ToString(buff));
         //再多新建一个
     }
     catch 
     {
         socket.Close();
         Debug.Log("net error");
     }
     socket.BeginReceive(buff, 0, 1024, SocketFlags.None, ReceiveCallBack, buff);//形成闭环
 }

注册成功时客户端收到的内容:1E

注册失败时客户端收到的内容:1F

读取,加入队列的代码如下:

cs 复制代码
private void readMessage(byte[] message)//处理所收到的信息
{
    MemoryStream ms = new MemoryStream(message, 0, message.Length);
    ByteArray ba = new ByteArray(ms);//这个模型是自定义的
    SocketModel model = new SocketModel();
    model.type = ba.ReadInt();
    model.area = ba.ReadInt();
    model.command = ba.ReadInt();
    int length= ba.ReadInt();
    if (length>0)
    {
        model.message = ba.ReadUTFBytes((uint)length);
    }
    messageList.Add(model);//这个函数也是自定义的
    Debug.Log("readMessage并加入消息队列");
}

现在的问题是readMessage函数没有被调用。

相关推荐
别动我齐刘海1 小时前
Linux 系统调试学习1
linux·运维·服务器·c++·学习·机器学习·机器人
xier_ran2 小时前
【infra之路】AI 编译器学习笔记(二):重拾 C++——移动语义与 LLVM 风格的类型转换
人工智能·笔记·学习
li星野4 小时前
5 TYPES OF ADVERBS — One-Page Notes
学习
星恒随风5 小时前
Linux库的底层原理:ELF文件格式、静态链接、程序加载、虚拟地址空间与GOT/PLT详解
linux·运维·笔记·学习·状态模式
罗西的思考5 小时前
[Agent Memory / 强化学习] MemPO源码学习笔记 — (7)— 混合机制
笔记·学习
starsky762385 小时前
Agent学习——上下文工程(三)
学习
xier_ran7 小时前
【infra之路】AI 编译器学习笔记(四):PatternRewriter 与贪心 driver
人工智能·笔记·学习
小弥儿7 小时前
GitHub今日热榜 | 2026-10-12:pytorch 上升四位
人工智能·pytorch·学习·开源·github
AOI小白新手上路7 小时前
DeepLens 的课程学习自动设计与同源仿真论文综述
学习
老王爱玩车8 小时前
预处理详解
c语言·开发语言·学习