ET学习笔记

最近重新下载了ET3.3版本,之前在学习2.x版本的时候更多的是偏向应用,没有深入的研究内部实现的原理,想服务器架构,session与TChannel的关系,Actor消息的机制与实现,ECS架构,通信协议的底层基础等等,都没有深入学习,最近项目不太忙,有时间沉下心仔细研究重新梳理一下。

网络连接是如何实现的:
链接分为:a)监听他人的连接。b)连接他人。

a)监听他人的连接:服务器在启动的时候会分别创建NetInnerComponent和NetOuterComponent,并把自己的内网地址、外网地址传进去,见代码:
Game.Scene.AddComponent<NetInnerComponent, IPEndPoint>(innerConfig.IPEndPoint);
Game.Scene.AddComponent<NetOuterComponent, IPEndPoint>(outerConfig.IPEndPoint);

在他们的父类NetworkComponent Awake方法里面,根据是TCP还是KCP来判断是创建TService还是KService,这里以TCP为例,TService构造方法里面,根据传进来的IPEndPoint,创建一个TcpListener,来对该IPEndPoint进行监听。代码如下:
public TService(IPEndPoint ipEndPoint)
{
        this.acceptor = new TcpListener(ipEndPoint);
this.acceptor.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
this.acceptor.Server.NoDelay = true;
this.acceptor.Start();

}
什么时候会收到客户端发来的消息?

在下面这个方法里:
public override async Task<AChannel> AcceptChannel()
{
if (this.acceptor == null)
{
throw new Exception("service construct must use host and port param");
}
TcpClient tcpClient = await this.acceptor.AcceptTcpClientAsync();
TChannel channel = new TChannel(tcpClient, this);
this.idChannels[channel.Id] = channel;
return channel;
}
服务器收到客户端发来的连接请求后会创建一个TcpClient ,该项目中,会对TcpClient进行封装,创建一个TChannel,然后通过TChannel创建一个Session,如下代码:
public virtual async Task<Session> Accept()
{
AChannel channel = await this.Service.AcceptChannel();
Session session = ComponentFactory.CreateWithId<Session, NetworkComponent, AChannel>(IdGenerater.GenerateId(), this, channel);
session.Parent = this;
channel.ErrorCallback += (c, e) =>
{
session.Error = e;
this.Remove(session.Id);
};
this.sessions.Add(session.Id, session);
return session;
}

在接收到连接之后,在断开连接之前,所有的该客户端发过来的消息都在创建的Session里面接受,上面过程只负责第一次连接的时候。Session接收消息代码如下:

可以看到Session接收消息还是通过Channel里实现的。

我们再来看Channel里面的实现:





当TChannel里面的this.parser.GetPacket()成功后,Session会执行Run(packet)对协议进行解析。


b)如何连接他人的IP

NetworkComponent里面创建无参TService。在客户端或者服务器内网想要连接某IP的时候,传入IPEndPoint,代码如下:


在TService里面创建TcpClient和TChannel,在TChannel里面开启连接,代码如下:




猜你喜欢

转载自blog.csdn.net/younne0915/article/details/80523317