-
Notifications
You must be signed in to change notification settings - Fork 0
/
nutsog.go
111 lines (89 loc) · 1.78 KB
/
nutsog.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"flag"
"fmt"
"net"
"os"
"time"
)
var dest string
var verbosity int
func init() {
flag.StringVar(&dest, "dest", "localhost", "host:port to connect")
flag.IntVar(&verbosity, "verbosity", 0, "Verbosity level")
flag.Parse()
}
func StderrPrintln(a ...interface{}) (n int, err error) {
return fmt.Fprintln(os.Stderr, a)
}
func SogPrintln(a ...interface{}) (n int, err error) {
if verbosity > 0 {
return fmt.Println(a)
}
return 0, nil
}
func main() {
SogPrintln(os.Args[0])
_, err := net.ResolveTCPAddr("tcp", dest)
if err != nil {
fmt.Println("net.ResolveTCPAddr", err)
return
}
SogPrintln(dest)
var conn, err2 = net.Dial("tcp", dest)
if err2 != nil {
fmt.Println("net.Dial error:", err2)
return
}
SogPrintln(conn.LocalAddr(), " -> ", conn.RemoteAddr())
loop(conn)
}
func loop(conn net.Conn) {
errNet := make(chan error)
errStd := make(chan error)
go handleReadBuf(os.Stdin, conn, errStd)
go handleReadBuf(conn, os.Stdout, errNet)
for {
select {
case err := <-errNet:
SogPrintln("Error Conn", err)
conn.Close()
time.Sleep(10)
return
case err := <-errStd:
SogPrintln("Error Std", err)
os.Stdin.Close()
time.Sleep(10)
return
}
}
}
type SogConn interface {
Read(b []byte) (n int, err error)
Write(b []byte) (n int, err error)
Close() error
}
func handleWrite(conn SogConn, errCh chan error, b []byte) {
tot := len(b)
n, err := conn.Write(b)
if err != nil {
errCh <- err
if n != tot {
SogPrintln("Short write", n, "of", tot, "bytes")
}
}
}
func handleReadBuf(conn SogConn, wconn SogConn, errCh chan error) {
for {
b := make([]byte, 512)
n, err := conn.Read(b)
if err != nil {
errCh <- err
break
}
handleWrite(wconn, errCh, b[:n])
}
}
func toBytes(s string) []byte {
return []byte(s)
}