Uma versão totalmente nova, o código foi bastante organizado, cada função é definida separadamente em um arquivo fonte go específico e a interface e a arquitetura são redefinidas.
-------- --------
| server | | client |
-------- --------
| |
-------------
|
-----------
| bootstrap |
-----------
|
-----------
| protocols |
-----------
|
---------
| handler |
---------
Definição de interface
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
}
Criar inicialização
func NewBootStrap ( config * Config , contextFactory * ContextFactory , connectionSetting func ( conn net. Conn )) Bootstrap
Entre eles, Config é usado principalmente para definir o limite do número de conexões Bootstrap e se deve ser processado simultaneamente. Pode ser necessário expandi-lo no futuro.
type Config struct {
//最大连接数
MaxConnection int
//最大并发处理个数
MaxConcurrentHandler int
//是否顺序处理消息,默认false,即可以并发处理消息
OrderHandler bool
}
O método func connectionSetting(conn net.Conn)
é usado principalmente para personalizar as propriedades de net.Conn ao criar uma conexão. Pode haver um método padrão após a otimização no futuro.
A criação do contextFactory requer o uso de
func NewContextFactory ( initContextFunc func ( context * Context )) * ContextFactory
Inicialize o Contexto ao criar o Contexto após estabelecer a conexão, como definir protocolo, manipulador, etc.
Inicialização desativada
Chamar o método Close() fechará todas as conexões gerenciadas pelo Bootstrap.
Criar servidor
Chame Bootstrap.NewServer()
para criar, == atualmente suporta apenas TCP==
Inicialização do servidor
Chame Server.Bind() para iniciar o monitoramento. Se você quiser ouvir várias portas, crie mais servidores. Você pode compartilhar um Bootstrap para gerenciar links.
CriarCliente
Chame Bootstrap.NewClient()
para criar, == atualmente suporta apenas TCP==
O cliente inicia
Ligue para 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 ()
}
Memorando: