-
Notifications
You must be signed in to change notification settings - Fork 0
/
send.go
64 lines (58 loc) · 1.54 KB
/
send.go
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
package core
import (
"fmt"
"log"
"net"
"github.com/DyCAPSTeam/DyCAPS/pkg/protobuf"
"github.com/DyCAPSTeam/DyCAPS/pkg/utils"
"google.golang.org/protobuf/proto"
)
//MAXMESSAGE is the size of channels
var MAXMESSAGE = 1024
//MakeSendChannel returns a channel to send messages to hostIP
func MakeSendChannel(hostIP string, hostPort string) chan *protobuf.Message {
var addr *net.TCPAddr
var conn *net.TCPConn
var err1, err2 error
//Retry to connet to node
retry := true
for retry {
addr, err1 = net.ResolveTCPAddr("tcp4", hostIP+":"+hostPort)
conn, err2 = net.DialTCP("tcp4", nil, addr)
conn.SetKeepAlive(true)
if err1 != nil || err2 != nil {
log.Fatalln(err1)
log.Fatalln(err2)
// retry = true
} else {
retry = false
}
}
//Make the send channel and the handle func
sendChannel := make(chan *protobuf.Message, MAXMESSAGE)
go func(conn *net.TCPConn, channel chan *protobuf.Message) {
for {
//Pop protobuf.Message form sendchannel
m := <-(channel)
//Do Marshal
byt, err1 := proto.Marshal(m)
if err1 != nil {
fmt.Printf("Send message ERROR:%v\n", err1)
log.Fatalln(err1)
}
//Send bytes
length := len(byt)
_, err2 := conn.Write(utils.IntToBytes(length))
_, err3 := conn.Write(byt)
if err2 != nil {
fmt.Printf("Send message ERROR:%v\n", err2)
log.Fatalln("The send channel has broken down!", err2)
}
if err3 != nil {
fmt.Printf("Send message ERROR:%v\n", err3)
log.Fatalln("The send channel has broken down!", err3)
}
}
}(conn, sendChannel)
return sendChannel
}