1 Star 0 Fork 1

7tima/Go网络连接管理

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
default_connection.go 2.71 KB
一键复制 编辑 原始数据 按行查看 历史
shallot 提交于 2020-09-10 09:26 . 初步完成连接的公共接口。
/*
Copyright 2020 XiaochengTech
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package connections
import (
"io"
"net"
"time"
)
// 默认连接结构体,必须继承后实现缺少的接口才能使用
type DefaultConnection struct {
// 内部属性
identifier string // 唯一标志
isPassive bool // 是否是被动连接(不重连),还是主动连接(自动重连)
conn net.Conn // 底层连接
address string // 底层地址
closed bool // 是否已关闭
connectTimeout time.Duration // 连接超时时间
readTimeout time.Duration // 读超时
writeTimeout time.Duration // 写超时
// 信息通道
readBuf chan []byte // 正常消息的读取通道
readError chan error // 错误消息的读取通道
// 事件回调
onConnect func(id string, addr string)
onWrite func(id string, buf []byte, n int, err error)
onClose func(id string)
}
// (接口)读取信息
func (m DefaultConnection) Read() (buf []byte, err error) {
// 从正常信息通道和错误信息通道读取信息
var ok bool
select {
case buf, ok = <-m.readBuf:
case err, ok = <-m.readError:
}
// 如果连接已关闭
if m.closed || !ok {
err = io.EOF
return
}
return
}
// (接口)关闭连接
func (m *DefaultConnection) Close() {
// 已关闭
if m.closed {
return
}
// 置标志为关闭状态
m.closed = true
// 关闭连接
_ = m.conn.Close()
// 通知外界
if m.onClose != nil {
m.onClose(m.identifier)
}
return
}
// (接口)设置连接超时
func (m *DefaultConnection) SetConnectTimeout(d time.Duration) {
m.connectTimeout = d
}
// (接口)设置读超时
func (m *DefaultConnection) SetReadTimeout(d time.Duration) {
m.readTimeout = d
}
// (接口)设置写超时
func (m *DefaultConnection) SetWriteTimeout(d time.Duration) {
m.writeTimeout = d
}
// (接口)唯一标志
func (m DefaultConnection) Identifier() string {
return m.identifier
}
// (接口)是否是被动连接/主动连接
func (m DefaultConnection) IsPassive() bool {
return m.isPassive
}
// (接口)底层连接
func (m DefaultConnection) Conn() net.Conn {
return m.conn
}
// (接口)是否已关闭
func (m DefaultConnection) IsClosed() bool {
return m.closed
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/monster1213/connections.git
git@gitee.com:monster1213/connections.git
monster1213
connections
Go网络连接管理
master

搜索帮助