-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongConnJob.go
More file actions
83 lines (69 loc) · 1.39 KB
/
LongConnJob.go
File metadata and controls
83 lines (69 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package gserver
import (
"context"
"github.com/gw123/glog"
"github.com/gw123/gserver/contracts"
"github.com/pkg/errors"
"github.com/spf13/viper"
"net"
"time"
)
type LongConnJob struct {
timeout time.Duration
timer *time.Timer
cancelFunc context.CancelFunc
stopFlag bool
conn net.Conn
}
func NewLongConnJob(conn net.Conn, timeout time.Duration) *LongConnJob {
requestJob := &LongConnJob{
timeout: timeout,
conn: conn,
}
return requestJob
}
func (job *LongConnJob) Run(ctx context.Context) error {
debug := viper.GetBool("debug")
if job.conn == nil {
return errors.New("conn is nil")
}
var flag = true
defer func() {
flag = false
}()
packer := NewDataPack()
var count = 0
go func() {
for flag {
glog.Infof("count %d", count)
time.Sleep(time.Second)
select {
case <-ctx.Done():
flag = false
// todo signal client server has close
job.conn.Close()
break
default:
}
}
}()
for flag {
count++
recvMsg, err := packer.UnPackFromConn(job.conn)
if err != nil {
glog.WithErr(err).Errorf("packer unPackFromConn err")
return err
}
if debug {
glog.Infof("sendMsg msgId", recvMsg.MsgId, recvMsg.Length)
}
sendMsg := contracts.NewMsg(1, []byte("server"))
buf, err := packer.Pack(sendMsg)
if err != nil {
glog.WithErr(err).Errorf("packer pack err")
continue
}
job.conn.Write(buf)
}
return nil
}