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
}建立Bootstrap
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進行初始化設定,如設定protocol,handler等
Bootstrap關閉
呼叫Close()方法,將會關閉由Bootstrap管理的所有Connection.
建立Server
呼叫Bootstrap.NewServer()來建立,==目前只支援TCP==
Server的啟動
呼叫Server.Bind()來啟動監聽.如果想要監聽多個端口,請創建多了Server,可以共用一個Bootstrap來管理鏈接
創建Client
呼叫Bootstrap.NewClient()來建立,==目前只支援TCP==
Client啟動
呼叫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 ()
}備忘: