项目作者: coffeehc

项目描述 :
简单的net框架
高级语言: Go
项目地址: git://github.com/coffeehc/netx.git
创建时间: 2013-12-02T14:03:03Z
项目社区:https://github.com/coffeehc/netx

开源协议:MIT License

关键词:
golang net netty tcp

下载


netx —简单的一个Net框架

GoDoc

2.0.0 架构

一个全新版本,将代码进行了大的整理,每个功能都单独定义到具体的go源文件中,并且重新定义了接口以及架构

  1. -------- --------
  2. | server | | client |
  3. -------- --------
  4. | |
  5. -------------
  6. |
  7. -----------
  8. | bootstrap |
  9. -----------
  10. |
  11. -----------
  12. | protocols |
  13. -----------
  14. |
  15. ---------
  16. | handler |
  17. ---------

Bootstrap

接口定义

  1. type Bootstrap interface {
  2. //创建一个新的Server
  3. NewServer(netType, host string) *Server
  4. //创建一个信的Client
  5. NewClient(netType, host string) *Client
  6. //当连接创立的时候需要被调用,可用于自定义扩展
  7. Connection(conn net.Conn) (*Context, error)
  8. //关闭多有的链接
  9. Close() error
  10. //获取统计接口信息
  11. GetStatInfo() StatInfo
  12. }

创建Bootstrap

  1. func NewBootStrap(config *Config, contextFactory *ContextFactory, connectionSetting func(conn net.Conn)) Bootstrap

其中Config主要用于设置Bootstrap连接数限制以及是否并发处理,将来可能还需要扩展

  1. type Config struct {
  2. //最大连接数
  3. MaxConnection int
  4. //最大并发处理个数
  5. MaxConcurrentHandler int
  6. //是否顺序处理消息,默认false,即可以并发处理消息
  7. OrderHandler bool
  8. }

func connectionSetting(conn net.Conn)方法主要是在创建连接的时候对net.Conn的属性进行自定义的扩展,没有默认方法,将来优化后可能会有默认方法

contextFactory的创建需要使用

  1. func NewContextFactory(initContextFunc func(context *Context)) *ContextFactory

在建立连接后创建Context的时候对Context进行初始化设置,如设置protocol,handler等

Bootstrap关闭

调用Close()方法,将会关闭由Bootstrap管理的所有Connection.

Server&Client

创建Server

调用Bootstrap.NewServer()来创建,==目前仅支持TCP==

Server的启动

调用Server.Bind()来启动监听.如果想要监听多个端口,请创建多了Server,可以共用一个Bootstrap来管理链接

创建Client

调用Bootstrap.NewClient()来创建,==目前仅支持TCP==

Client启动

调用Client.Client(timeout time.Duration)

例子

  1. func TestServer(t *testing.T) {
  2. contextFactory := NewContextFactory(func(context *Context) {
  3. //设置
  4. context.SetProtocols([]Protocol{new(defaultProtocol)})
  5. context.SetHandler(new(testHandler))
  6. })
  7. bootstrap := NewBootStrap(new(Config), contextFactory, nil)
  8. server := bootstrap.NewServer("tcp", "127.0.0.1:9991")
  9. err := server.Bind()
  10. if err != nil {
  11. t.Fatalf("启动服务器出现错误:%s", err)
  12. }
  13. client := bootstrap.NewClient("tcp", "127.0.0.1:9991")
  14. err = client.Connect(3 * time.Second)
  15. if err != nil {
  16. t.Fatalf("连接服务器出现错误:%s", err)
  17. }
  18. context := client.GetContext()
  19. for i := 0; i < 10; i++ {
  20. context.Write([]byte(fmt.Sprintln("开始了\nnext")))
  21. }
  22. time.Sleep(time.Millisecond * 300)
  23. context.Close()
  24. server.Close()
  25. bootstrap.Close()
  26. }

备忘:

  1. 考虑提供https://github.com/google/gopacket.git的引用
  2. 考虑内存池的使用