Go语言实现长连接并发框架 - 连接
文章目录
- 前言
- 接口
- 结构体
- 接口实现
- 最后
前言
你好,我是醉墨居士,我在上一篇博客中写到,我要实现长连接并发框架,这篇博客我们就一起实现客户端连接的封装,方便我们后续的使用和管理
接口
trait/connection.go
// Socket 底层的长连接套接字
type Socket interface {net.ConnFile() (*os.File, error)
}// Connection 连接模块抽象层
type Connection interface {SocketID() int32Send(msgID uint16, data []byte) errorStop()
}
结构体
gcore/connection.go
// Connection 连接模块
type Connection struct {// 底层连接的套接字trait.Socket// 连接的唯一标识id int32isClosed bool//防止连接并发写的锁writeLock *sync.MutexexitCh chan struct{}
}// NewConnection 创建一个新的连接对象
func NewConnection(connID int32, socket trait.Socket) *Connection {return &Connection{id: connID,Socket: socket,isClosed: false,exitCh: make(chan struct{}, 1),}
}
接口实现
gcore/connection.go
// ID 返回连接ID
func (c *Connection) ID() int32 {return c.id
}// Send 发送消息给客户端
func (c *Connection) Send(msgID uint16, data []byte) error {if c.isClosed {return errors.New("connection is closed when send message")}//封装message消息message := gpack.NewMessage(msgID, data)//封包response := gpack.Pack(message)c.writeLock.Lock()defer c.writeLock.Unlock()_, err := c.Socket.Write(response)return err
}// Stop 关闭连接
func (c *Connection) Stop() {if c.isClosed {return}c.isClosed = truec.Socket.Close()close(c.exitCh)
}
最后
我是醉墨居士,我们已经完成客户端连接的基本封装,后续我们会基于这个封装的连接完善我们更多的功能