加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
connection_udp.go 2.42 KB
一键复制 编辑 原始数据 按行查看 历史
shallot 提交于 2020-09-10 18:13 . 添加TCP和UDP的连接实现。
/*
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"
)
// UDP读取缓冲区的长度
const UDP_BUFFER_SIZE = 4 * 1024
// UDP连接实现
type ConnectionUDP struct {
DefaultConnection
}
// (接口)主动连接
func (m *ConnectionUDP) Connect(addr string) (err error) {
m.address = addr
// 连接
if m.connectTimeout > 0 {
m.conn, err = net.DialTimeout(UDP, addr, m.connectTimeout)
} else {
m.conn, err = net.Dial(UDP, addr)
}
// 事件回调
if m.onConnect != nil {
m.onConnect(m.identifier, addr)
}
return
}
// (接口)写入信息
func (m ConnectionUDP) Write(buf []byte) (n int, err error) {
// 判断连接是否已关闭
if m.closed {
// 被动模式直接返回
if m.isPassive {
return
}
// 主动模式自动重连
if err = m.Connect(m.address); err != nil {
return
}
}
// 判断是否有写超时
if m.writeTimeout > 0 {
if err = m.conn.SetWriteDeadline(time.Now().Add(m.writeTimeout)); err != nil {
return
}
}
// 写入实际连接
n, err = m.conn.Write(buf)
// 通知外界
if m.onWrite != nil {
m.onWrite(m.identifier, buf, n, err)
}
return
}
// UDP被动连接读取数据包
func (m ConnectionUDP) udpPassiveReader(receiver chan []byte) {
for {
buf, ok := <-receiver
if !ok {
return
}
m.readBuf <- buf
}
}
// UDP主动连接读取数据包
func (m ConnectionUDP) udpActiveReader() {
buf := make([]byte, UDP_BUFFER_SIZE)
for {
// 连接关闭
if m.closed {
if err := m.Connect(m.address); err != nil {
time.Sleep(1 * time.Second)
continue
}
}
// 判断读超时
if m.readTimeout > 0 {
if e := m.conn.SetReadDeadline(time.Now().Add(m.readTimeout)); e != nil {
continue
}
}
// 接收数据包
n, err := m.conn.Read(buf)
if err != nil {
if err == io.EOF {
m.Close()
continue
}
m.readError <- err
continue
}
m.readBuf <- buf[0:n]
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化