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函数没有被调用。

相关推荐
iFulling9 小时前
【计算机网络】第四章:网络层(上)
学习·计算机网络
香蕉可乐荷包蛋10 小时前
AI算法之图像识别与分类
人工智能·学习·算法
xiaoli232710 小时前
课题学习笔记1——文本问答与信息抽取关键技术研究论文阅读(用于无结构化文本问答的文本生成技术)
笔记·学习
人生游戏牛马NPC1号10 小时前
学习 Flutter (四):玩安卓项目实战 - 中
android·学习·flutter
LGGGGGQ11 小时前
嵌入式学习-PyTorch(7)-day23
人工智能·pytorch·学习
stm 学习ing12 小时前
Python暑期学习笔记3
笔记·python·学习
屁股割了还要学12 小时前
【C语言进阶】内存函数
c语言·开发语言·学习·算法·青少年编程
靴子学长12 小时前
Lotus-基于大模型的查询引擎 -开源学习整理
python·学习·自然语言处理
Littlewith13 小时前
Node.js:创建第一个应用
服务器·开发语言·后端·学习·node.js
ROOKIE Shawn13 小时前
mysql学习笔记
笔记·学习