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 == 0 {
        return false
    }
    return true
}

//接收内容
func (q *QRequest) ReceiveData(timeout time.Duration) []byte {
    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()
}

 

posted @ 2017-01-31 22:00  ﹏Sakura  阅读(1199)  评论(0编辑  收藏  举报