Golang 发送和接收数据公共类

1package RequestCenter 2 3import ( 4 "bytes" 5 "io" 6 "net" 7 "runtime" 8 "strings" 9 "time" 10) 11 12//请求结构体 13type QRequest struct { 14 conn net.Conn 15} 16 17//构造函数 18func CreateRequest(typename string, host string) *QRequest { 19 request := new(QRequest) 20 //GC析构前调用 21 runtime.SetFinalizer(request, func(q *QRequest) { 22 q.Close() 23 }) 24 conn, err := net.Dial(typename, host) 25 if err == nil { 26 request.conn = conn 27 return request 28 } 29 return nil 30} 31 32func CreateRequestWithConn(conn net.Conn) *QRequest { 33 request := new(QRequest) 34 //GC析构前调用 35 runtime.SetFinalizer(request, func(q *QRequest) { 36 q.Close() 37 }) 38 request.conn = conn 39 return request 40} 41 42//析构函数 43func (q *QRequest) Close() { 44 if !q.CheckReq() { 45 return 46 } 47 q.conn.SetDeadline(time.Now()) 48 q.conn.Close() 49} 50 51//发送内容 52func (q *QRequest) SendData(heads []string, body []byte) bool { 53 if !q.CheckReq() { 54 return false 55 } 56 var headsStr string 57 if len(heads) > 0 { 58 headsStr = strings.Join(heads, "\r\n") + string(body) 59 count, err := q.conn.Write([]byte(headsStr)) 60 if err != nil || count == 0 { 61 return false 62 } 63 return true 64 } else { 65 count, err := q.conn.Write(body) 66 if err == nil || count == 0 { 67 return false 68 } 69 return true 70 } 71 72} 73 74//接收内容 75func (q *QRequest) ReceiveData(timeout time.Duration) []byte { 76 if !q.CheckReq() { 77 return nil 78 } 79 if timeout > 0 { 80 q.conn.SetReadDeadline(time.Now().Add(time.Millisecond * timeout)) 81 } 82 var buf bytes.Buffer 83 buffer := make([]byte, 8192) 84 for { 85 sizenew, err := q.conn.Read(buffer) 86 buf.Write(buffer[:sizenew]) 87 if err == io.EOF || sizenew < 8192 { 88 break 89 } 90 } 91 return buf.Bytes() 92} 93 94func (q *QRequest) CheckReq() bool { 95 if q == nil || q.conn == nil { 96 return false 97 } 98 return true 99}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java将前端的json数组字符串转换为列表

记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang

go 协程

packageutilsimport("bytes""fmt""runtime""strconv")_/\__获取协程__ID\/_funcGetGoroutineID(){b:make(\\byte,64)b\b\:runtime.Stack(b,false)\b\