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

相关推荐
水月wwww37 分钟前
vue学习之组件与标签
前端·javascript·vue.js·学习·vue
952361 小时前
数据结构-链表
java·数据结构·学习
找了一圈尾巴1 小时前
软件架构设计学习-基本概念
学习·软件架构
驯狼小羊羔1 小时前
学习随笔-require和import
前端·学习
2301_796512522 小时前
Rust编程学习 - 问号运算符会return一个Result 类型,但是如何使用main函数中使用问号运算符
开发语言·学习·算法·rust
deng-c-f2 小时前
Linux C/C++ 学习日记(47):dpdk(八):UDP的pps测试:内核 VS dpdk
学习
d111111111d2 小时前
STM32外设学习--TIM定时器--编码器接口
stm32·嵌入式硬件·学习
喜欢吃燃面2 小时前
Linux:make自动化和实战演练
linux·学习
循环过三天8 小时前
3.4、Python-集合
开发语言·笔记·python·学习·算法
昌sit!10 小时前
Linux系统性基础学习笔记
linux·笔记·学习