代码拉取完成,页面将自动刷新
/*
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]
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。