Golang 发送和接收数据公共类

原创
2017/01/25 12:02
阅读数 98
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
}

 

展开阅读全文
0
1 收藏
分享
加载中
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部