Golang 发送和接收数据公共类

package RequestCenter

import (
"bytes"
"io"
"net"
"runtime"
"strings"
"time"
) //请求结构体
type QRequest struct {
conn net.Conn
} //构造函数
func CreateRequest(typename string, host string) *QRequest {
request := new(QRequest)
//GC析构前调用
runtime.SetFinalizer(request, func(q *QRequest) {
q.Close()
})
conn, err := net.Dial(typename, host)
if err == nil {
request.conn = conn return request
}
return nil
} //析构函数
func (q *QRequest) Close() {
q.conn.SetDeadline(time.Now())
q.conn.Close()
} //发送内容
func (q *QRequest) SendData(heads []string, body string) bool {
headsStr := strings.Join(heads, "\r\n") + body
count, err := q.conn.Write([]byte(headsStr))
if err != nil || count == {
return false
}
return true
} //接收内容
func (q *QRequest) ReceiveData(timeout time.Duration) []byte {
if timeout > {
q.conn.SetReadDeadline(time.Now().Add(time.Millisecond * timeout))
}
var buf bytes.Buffer
buffer := make([]byte, )
for {
sizenew, err := q.conn.Read(buffer)
buf.Write(buffer[:sizenew])
if err == io.EOF || sizenew < {
break
}
}
return buf.Bytes()
}
上一篇:NGif, Animated GIF Encoder for .NET


下一篇:【CF850E】Random Elections FWT