netx
1.0.0
新しいバージョンでは、コードが大幅に整理され、各関数が特定の go ソース ファイルで個別に定義され、インターフェイスとアーキテクチャが再定義されています。
-------- --------
| server | | client |
-------- --------
| |
-------------
|
-----------
| bootstrap |
-----------
|
-----------
| protocols |
-----------
|
---------
| handler |
---------
インターフェースの定義
type Bootstrap interface {
//创建一个新的Server
NewServer ( netType , host string ) * Server
//创建一个信的Client
NewClient ( netType , host string ) * Client
//当连接创立的时候需要被调用,可用于自定义扩展
Connection ( conn net. Conn ) ( * Context , error )
//关闭多有的链接
Close () error
//获取统计接口信息
GetStatInfo () StatInfo
}
ブートストラップの作成
func NewBootStrap ( config * Config , contextFactory * ContextFactory , connectionSetting func ( conn net. Conn )) Bootstrap
このうち Config は主に Bootstrap 接続数の制限や同時処理を行うかどうかを設定するために使用されます。将来的には拡張する必要があるかもしれません。
type Config struct {
//最大连接数
MaxConnection int
//最大并发处理个数
MaxConcurrentHandler int
//是否顺序处理消息,默认false,即可以并发处理消息
OrderHandler bool
}
func connectionSetting(conn net.Conn)
メソッドは、主に接続作成時に net.Conn のプロパティをカスタマイズするために使用されます。デフォルトのメソッドはありません。将来、最適化後にデフォルトのメソッドが存在する可能性があります。
contextFactory の作成には、以下を使用する必要があります。
func NewContextFactory ( initContextFunc func ( context * Context )) * ContextFactory
接続確立後のContext作成時に、プロトコルやハンドラの設定など、Contextの初期化を行います。
ブートストラップがオフ
Close() メソッドを呼び出すと、Bootstrap によって管理されているすべての接続が閉じられます。
サーバーの作成
Bootstrap.NewServer()
を呼び出して作成します。== 現在は TCP のみをサポートしています==
サーバーの起動
Server.Bind() を呼び出して監視を開始します。複数のポートをリッスンする場合は、ブートストラップを共有してリンクを管理できます。
クライアントの作成
Bootstrap.NewClient()
を呼び出して作成します。== 現在は TCP== のみをサポートしています
クライアントの起動
Call Client.Client(timeout time.Duration)
func TestServer ( t * testing. T ) {
contextFactory := NewContextFactory ( func ( context * Context ) {
//设置
context . SetProtocols ([] Protocol { new ( defaultProtocol )})
context . SetHandler ( new ( testHandler ))
})
bootstrap := NewBootStrap ( new ( Config ), contextFactory , nil )
server := bootstrap . NewServer ( "tcp" , "127.0.0.1:9991" )
err := server . Bind ()
if err != nil {
t . Fatalf ( "启动服务器出现错误:%s" , err )
}
client := bootstrap . NewClient ( "tcp" , "127.0.0.1:9991" )
err = client . Connect ( 3 * time . Second )
if err != nil {
t . Fatalf ( "连接服务器出现错误:%s" , err )
}
context := client . GetContext ()
for i := 0 ; i < 10 ; i ++ {
context . Write ([] byte ( fmt . Sprintln ( "开始了n next" )))
}
time . Sleep ( time . Millisecond * 300 )
context . Close ()
server . Close ()
bootstrap . Close ()
}
メモ: