Golang 发送和接收数据公共类

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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 CreateRequestWithConn(conn net.Conn) *QRequest {
	request := new(QRequest)
	//GC析构前调用
	runtime.SetFinalizer(request, func(q *QRequest) {
		q.Close()
	})
	request.conn = conn
	return request
}

//析构函数
func (q *QRequest) Close() {
	if !q.CheckReq() {
		return
	}
	q.conn.SetDeadline(time.Now())
	q.conn.Close()
}

//发送内容
func (q *QRequest) SendData(heads []string, body []byte) bool {
	if !q.CheckReq() {
		return false
	}
	var headsStr string
	if len(heads) > 0 {
		headsStr = strings.Join(heads, "\r\n") + string(body)
		count, err := q.conn.Write([]byte(headsStr))
		if err != nil || count == 0 {
			return false
		}
		return true
	} else {
		count, err := q.conn.Write(body)
		if err == nil || count == 0 {
			return false
		}
		return true
	}

}

//接收内容
func (q *QRequest) ReceiveData(timeout time.Duration) []byte {
	if !q.CheckReq() {
		return nil
	}
	if timeout > 0 {
		q.conn.SetReadDeadline(time.Now().Add(time.Millisecond * timeout))
	}
	var buf bytes.Buffer
	buffer := make([]byte, 8192)
	for {
		sizenew, err := q.conn.Read(buffer)
		buf.Write(buffer[:sizenew])
		if err == io.EOF || sizenew < 8192 {
			break
		}
	}
	return buf.Bytes()
}

func (q *QRequest) CheckReq() bool {
	if q == nil || q.conn == nil {
		return false
	}
	return true
}

 

转载于:https://my.oschina.net/u/252343/blog/830259

你可能感兴趣的:(Golang 发送和接收数据公共类)