-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnet.go
55 lines (47 loc) · 1.09 KB
/
net.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
package main
import (
"fmt"
"io"
"io/ioutil"
"net"
"strings"
"time"
)
const sampleData = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
// download reads data from `conn` and returns the number of bytes read.
func download(conn net.Conn, timeout time.Duration) (bytes int64, err error) {
if timeout > 0 {
conn.SetDeadline(time.Now().Add(timeout))
}
bytes, _ = io.Copy(ioutil.Discard, conn)
return
}
// upload writes data to `conn` and returns the number of bytes written.
func upload(conn net.Conn, timeout time.Duration) (bytes int64, err error) {
if timeout > 0 {
conn.SetDeadline(time.Now().Add(timeout))
}
chunk := strings.Repeat(sampleData, 256)
for {
n, err := conn.Write([]byte(chunk))
if err != nil {
break
}
bytes += int64(n)
}
return
}
// echo echoes all received lines back to the client.
func echo(conn net.Conn, timeout time.Duration) {
if timeout > 0 {
conn.SetDeadline(time.Now().Add(timeout))
}
var msg string
for {
fmt.Fscanf(conn, "%s\r\n", &msg)
_, err := conn.Write([]byte(msg + "\r\n"))
if err != nil {
break
}
}
}