-
Notifications
You must be signed in to change notification settings - Fork 1
/
ping.go
83 lines (67 loc) · 2.23 KB
/
ping.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"log"
"os"
"time"
"github.com/driftluo/tentacle-go"
"github.com/driftluo/tentacle-go/protocols/ping"
"github.com/driftluo/tentacle-go/secio"
"github.com/multiformats/go-multiaddr"
)
func main() {
args := os.Args
if len(args) == 2 {
if args[1] == "server" {
log.Println("Starting server ...")
server()
return
}
}
log.Println("Starting client ...")
client()
}
type pingCallback struct{}
func (p *pingCallback) ReceivedPing(ctx *tentacle.ProtocolContextRef) {
log.Println("received ping from: ", ctx.Key.PeerID().Bese58String())
}
func (p *pingCallback) ReceivedPong(ctx *tentacle.ProtocolContextRef, t time.Duration) {
log.Println("received pong from: ", ctx.Key.PeerID().Bese58String(), t)
}
func (p *pingCallback) Timeout(ctx *tentacle.ProtocolContext, id tentacle.SessionID) {
log.Println("peer timeout: ", ctx.Key.PeerID().Bese58String())
}
func (p *pingCallback) UnexpectedError(ctx *tentacle.ProtocolContextRef) {
log.Println("unexpected error: ", ctx.Key.PeerID().Bese58String())
}
type simpleHandler struct{}
func (s *simpleHandler) HandleError(ctx *tentacle.ServiceContext, err tentacle.ServiceError) {
log.Println("service error: ", err.String())
}
func (s *simpleHandler) HandleEvent(ctx *tentacle.ServiceContext, event tentacle.ServiceEvent) {
log.Println("service event: ", event.String())
}
func createMeta(pid tentacle.ProtocolID) tentacle.ProtocolMeta {
return tentacle.DefaultMeta().ID(pid).ServiceHandle(ping.NewProtocol(&pingCallback{}, 5*time.Second, 15*time.Second)).Build()
}
func client() {
client := tentacle.DefaultServiceBuilder().InsertProtocol(createMeta(tentacle.ProtocolID(1))).KeyPair(secio.GenerateSecp256k1()).Build(&simpleHandler{})
addr, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1/tcp/1337")
client.Dial(addr, tentacle.TargetProtocol{Tag: tentacle.All})
for {
if client.IsShutdown() {
break
}
time.Sleep(20 * time.Second)
}
}
func server() {
server := tentacle.DefaultServiceBuilder().InsertProtocol(createMeta(tentacle.ProtocolID(1))).KeyPair(secio.GenerateSecp256k1()).Build(&simpleHandler{})
addr, _ := multiaddr.NewMultiaddr("/ip4/127.0.0.1/tcp/1337")
server.Listen(addr)
for {
if server.IsShutdown() {
break
}
time.Sleep(20 * time.Second)
}
}