注册过程最后一步,有这个基础,登录也非常简单了。
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函数没有被调用。