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

相关推荐
西岸行者3 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
悠哉悠哉愿意3 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
别催小唐敲代码3 天前
嵌入式学习路线
学习
毛小茛3 天前
计算机系统概论——校验码
学习
babe小鑫3 天前
大专经济信息管理专业学习数据分析的必要性
学习·数据挖掘·数据分析
winfreedoms3 天前
ROS2知识大白话
笔记·学习·ros2
在这habit之下3 天前
Linux Virtual Server(LVS)学习总结
linux·学习·lvs
我想我不够好。3 天前
2026.2.25监控学习
学习
im_AMBER3 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
CodeJourney_J3 天前
从“Hello World“ 开始 C++
c语言·c++·学习