解析addPeer操作
从handle(peer)倒推,寻找被调用关系
在p2p.Server.run()
函数,无限for
循环中,执行select
中case c := <-srv.addpeer:
分支的操作,进行handshake
,并且goroutine
启动Server.runPeer()
,并进一步调用peer.run()
,最终在startProtocols()
中调用proto.Run(p,rw)
,该Run()函数为handler.go
中NewProtocolManager()
中的函数类型变量Run
,该变量最终调用handle(peer)
,最终进行peer的其他操作。
p2p
中的Server
的成员变量addpeer
为conn
类型的channel
,在Server.checkpoint(c,srv.addpeer)
中的select
选择执行srv.addpeer <- c
,而checkpoint()
函数仅在Server.SetupConn()
中被调用,而SetupConn()
在Server.listenLoop()
中被调用,listenLoop()
函数中包含我们之前进行admin.addPeer()
所用到的enode
信息,由server.makeSelf()
函数生成
server.Start()
函数,首先初始化server
的成员变量,包含addpeer
、addstatic
等各种channel
;然后根据server
继承config
中的各种XXDiscovery
进行各自的操作。
==========================================================================
从admin.addPeer()正推,找调用关系
命令行运行admin.addPeer()
实际调用node/api.go
中的AddPeer(url)
,该函数根据url
初始化一个p2p/discover.Node
,然后调用p2p.server.AddPeer(node)
,最终返回true
p2p.server.AddPeer(node)
仅包含一个select
语句,将node
发送到srv.addstatic
,该channel
是p2p.Server
的一个discover.Node
类型的成员变量,定义如下:
在p2p.Server.Run()
函数,无限for
循环中,执行select
中case n := <-srv.addstatic:
分支的操作,调用dialstate.addStatic(n)
,该方法是dialer
接口的一个方法,由p2p/dial.go
中的dialstate
实现,该函数仅执行s.static[n.ID] = &dialTask{flags: staticDialedConn, dest: n}
,dialTask
的结构体如下:
s.static
在同一文件中的newTasks()
中被使用,该函数中通过for
循环遍历s.static
,然后针对每一个static
,调用s.checkDial(t.dest, peers)
进行连接检查,若没有错误产生,则会将static
添加到newtasks
中,另外,newTasks()
函数的返回值为newtasks
.
newTasks()
函数在Server.run()
中在函数类型变量scheduleTasks
中被调用,newTasks()
的返回值newtasks
随后作为startTasks()
的参数,startTasks()
会根据每个task
的类型,goroutine
启动Do(server)
函数;而scheduleTasks()
在随后的无限for
循环中被调用。
由于admin.addPeer
生成的task
为dialTask
,所以在startTasks()
中调用的Do()
函数如下:
该函数调用dial()
尝试实际连接,dial()
函数如下:
dial()
函数调用srv.Dialer.Dial(dest)
,该方法由func (t TCPDialer) Dial(dest *discover.Node) (net.Conn, error){}
实现,建立一个TCP连接,其后会调用go语言库函数,不再深究,如下:
随后,dial()
函数调用srv.SetupConn(mfd, t.flags, dest)
,如下:
SetupConn runs the handshakes and attempts to add the connection as a peer. It returns when the connection has been added as a peer or the handshakes have failed.
```go func (srv Server) SetupConn(fd net.Conn, flags connFlag, dialDest discover.Node) { // Prevent leftover pending conns from entering the handshake. ... 初始化handshake连接c,类型为conn
}
```
Last updated
Was this helpful?