当前位置: 首页 > news >正文

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)
}

最后

我是醉墨居士,我们已经完成客户端连接的基本封装,后续我们会基于这个封装的连接完善我们更多的功能


http://www.mrgr.cn/news/41832.html

相关文章:

  • #Swift :回调地狱 的解决 —— 通过 task/await 来替代 nested mutiple trailing closure 来进行 回调的解耦
  • 智能编码助手【通义灵码】实践指南
  • 容器适配器-stack、queue、priority_queue和仿函数
  • SpringBoot系列 启动流程
  • 登录功能开发 P167重点
  • 【Redis入门到精通九】Redis中的主从复制
  • Redis: 集群架构,优缺点和数据分区方式和算法
  • 软件修改工具----盘点那些免费的windows系统下的16进制编辑器 软件修改好帮手
  • Framebuffer学习
  • Python字符串string方法大全及使用方法[2]以及FastApi关闭接口文档、隐藏部分接口、关闭schemes的实现
  • CSS 实现楼梯与小球动画
  • (c#)unity中sqlite多线程同时开启事务会导致非常慢
  • python 棒棒糖图
  • python中的copy方法
  • Java - LeetCode面试经典150题 - 区间 (三)
  • 详解JavaScript中的闭包
  • 从零开始搭建UVM平台(八)-加入agent
  • Spring 框架和Spring Boot
  • Dave Cheney: Go语言之禅
  • 【AI知识点】损失函数(Loss Function)