A brand new version, the code has been greatly organized, each function is defined separately in a specific go source file, and the interface and architecture are redefined.
-------- --------
| server | | client |
-------- --------
| |
-------------
|
-----------
| bootstrap |
-----------
|
-----------
| protocols |
-----------
|
---------
| handler |
---------
Interface definition
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
}
Create Bootstrap
func NewBootStrap ( config * Config , contextFactory * ContextFactory , connectionSetting func ( conn net. Conn )) Bootstrap
Among them, Config is mainly used to set the limit on the number of Bootstrap connections and whether to process concurrently. It may need to be expanded in the future.
type Config struct {
//最大连接数
MaxConnection int
//最大并发处理个数
MaxConcurrentHandler int
//是否顺序处理消息,默认false,即可以并发处理消息
OrderHandler bool
}
The func connectionSetting(conn net.Conn)
method is mainly used to customize the properties of net.Conn when creating a connection. There is no default method. There may be a default method after optimization in the future.
The creation of contextFactory requires the use of
func NewContextFactory ( initContextFunc func ( context * Context )) * ContextFactory
Initialize the Context when creating the Context after establishing the connection, such as setting protocol, handler, etc.
Bootstrap off
Calling the Close() method will close all Connections managed by Bootstrap.
Create Server
Call Bootstrap.NewServer()
to create, == currently only supports TCP==
Server startup
Call Server.Bind() to start monitoring. If you want to listen to multiple ports, please create more servers. You can share a Bootstrap to manage links.
CreateClient
Call Bootstrap.NewClient()
to create, == currently only supports TCP==
Client starts
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 ()
}
Memo: