长安链源码分析之网络模块 net-liquid(3)
作者:李
- 2022-10-17 湖南
本文字数:936 字
阅读完需:约 1 分钟
本文已参与「开源摘星计划」,欢迎正在阅读的你加入。活动链接:https://github.com/weopenprojects/WeOpen-Star
core 包中有一个 host 包,里面有一个 notify
定义了一个接口,接口里面约定了 4 个函数
type Notifiee interface { // PeerConnected will be invoked when a new connection established. //当节点建立连接时触发 PeerConnected(pid peer.ID) // PeerDisconnected will be invoked when a connection disconnected. //当节点失去连接时触发 PeerDisconnected(pid peer.ID) // PeerProtocolSupported will be invoked when a peer support a new protocol. //当节点支持一个协议的时候触发 PeerProtocolSupported(protocolID protocol.ID, pid peer.ID) // PeerProtocolUnsupported will be invoked when a peer cancel supporting a new protocol. //当节点注销一个协议的时候触发 PeerProtocolUnsupported(protocolID protocol.ID, pid peer.ID)
复制代码
然后定义了一个结构体,实现了这个接口的所有函数
//NotifieeBundle 是Notifee 接口的实现type NotifieeBundle struct { PeerConnectedFunc func(peer.ID) PeerDisconnectedFunc func(peer.ID) PeerProtocolSupportedFunc func(protocolID protocol.ID, pid peer.ID) PeerProtocolUnsupportedFunc func(protocolID protocol.ID, pid peer.ID)}
func (n *NotifieeBundle) PeerConnected(pid peer.ID) { if n.PeerConnectedFunc != nil { n.PeerConnectedFunc(pid) }}
func (n *NotifieeBundle) PeerDisconnected(pid peer.ID) { if n.PeerDisconnectedFunc != nil { n.PeerDisconnectedFunc(pid) }}
func (n *NotifieeBundle) PeerProtocolSupported(protocolID protocol.ID, pid peer.ID) { if n.PeerProtocolSupportedFunc != nil { n.PeerProtocolSupportedFunc(protocolID, pid) }}
func (n *NotifieeBundle) PeerProtocolUnsupported(protocolID protocol.ID, pid peer.ID) { if n.PeerProtocolUnsupportedFunc != nil { n.PeerProtocolUnsupportedFunc(protocolID, pid) }}复制代码
这里面有一个有趣的用法
通过该句可以在编译期检测出,结构体是否实现了接口
var _ Notifiee = (*NotifieeBundle)(nil)
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 4
李
关注
还未添加个人签名 2018-05-04 加入
还未添加个人简介










评论