forked from aler9/dctk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
15download_streaming.go
74 lines (64 loc) · 1.44 KB
/
15download_streaming.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
// +build ignore
package main
import (
"fmt"
dctk "github.com/gswly/dctoolkit"
)
func main() {
client, err := dctk.NewClient(dctk.ClientConf{
HubUrl: "nmdc://hubip:411",
Nick: "mynick",
TcpPort: 3009,
UdpPort: 3009,
TcpTlsPort: 3010,
})
if err != nil {
panic(err)
}
// to stream a file you must know the exact file size, peer and TTH,
// or otherwise start a search like it is done in this example
var filePeer *dctk.Peer
fileSize := uint64(0)
fileTTH := dctk.TigerHash{}
fileCurPos := uint64(0)
dlStarted := false
const chunkMaxLen = uint64(1024 * 1024)
downloadNextChunk := func() {
if fileCurPos >= fileSize {
fmt.Println("download complete.")
client.Close()
return
}
chunkLen := chunkMaxLen
if (fileCurPos + chunkLen) > fileSize {
chunkLen = fileSize - fileCurPos
}
client.DownloadFile(dctk.DownloadConf{
Peer: filePeer,
TTH: fileTTH,
Start: fileCurPos,
Length: int64(chunkLen),
})
fileCurPos += chunkLen
}
client.OnHubConnected = func() {
client.Search(dctk.SearchConf{
Type: dctk.SearchTTH,
TTH: fileTTH,
})
}
client.OnSearchResult = func(res *dctk.SearchResult) {
if !dlStarted {
dlStarted = true
filePeer = res.Peer
fileSize = res.Size
fileTTH = res.TTH
downloadNextChunk()
}
}
client.OnDownloadSuccessful = func(d *dctk.Download) {
fmt.Printf("chunk available: %d\n", len(d.Content()))
downloadNextChunk()
}
client.Run()
}