代码拉取完成,页面将自动刷新
// Copyright 2019 Yang ZhongXi
// 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 core
import (
"errors"
"net"
)
// TCPStream TCP数据写入读取底层实现
type TCPStream struct {
conn *net.TCPConn
isOpened bool
receiver func(data []byte)
eventReporter func(err error)
}
// NewTCPStream 实例化
func NewTCPStream(conn *net.TCPConn, eventReporter func(err error)) *TCPStream {
return &TCPStream{conn: conn, eventReporter: eventReporter}
}
// Open 打开端口,并开启数据接收线程
func (t *TCPStream) Open() error {
if t.isOpened {
return errors.New("连接已打开")
}
go t.doWork()
return nil
}
// Close 关闭
func (t *TCPStream) Close() {
if !t.isOpened {
return
}
t.isOpened = false
t.conn.Close()
}
// Write 写入数据
func (t *TCPStream) Write(data []byte) error {
if !t.isOpened {
return errors.New("连接未打开")
}
_, err := t.conn.Write(data)
return err
}
// IsOpened 判断是否已打开
func (t *TCPStream) IsOpened() bool {
return t.isOpened
}
// SetReceiver 设置数据接收器
func (t *TCPStream) SetReceiver(receiver func(data []byte)) {
t.receiver = receiver
}
func (t *TCPStream) doWork() {
for t.isOpened {
buffer := make([]byte, 256)
l, err := t.conn.Read(buffer)
if err != nil {
if t.eventReporter != nil {
t.eventReporter(errors.New("读取数据失败:" + err.Error()))
}
break
}
if t.receiver != nil {
t.receiver(buffer[:l])
}
}
t.Close()
}
// TCPClientStream TCP客户端实现
type TCPClientStream struct {
stream *TCPStream
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。