-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathclient.go
73 lines (61 loc) · 1.1 KB
/
client.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
package main
import (
"bufio"
"fmt"
"net"
"os"
"sync"
)
const (
CONN_PORT = ":3333"
CONN_TYPE = "tcp"
MSG_DISCONNECT = "Disconnected from the server.\n"
)
var wg sync.WaitGroup
// Reads from the socket and outputs to the console.
func Read(conn net.Conn) {
reader := bufio.NewReader(conn)
for {
str, err := reader.ReadString('\n')
if err != nil {
fmt.Printf(MSG_DISCONNECT)
wg.Done()
return
}
fmt.Print(str)
}
}
// Reads from Stdin, and outputs to the socket.
func Write(conn net.Conn) {
reader := bufio.NewReader(os.Stdin)
writer := bufio.NewWriter(conn)
for {
str, err := reader.ReadString('\n')
if err != nil {
fmt.Println(err)
os.Exit(1)
}
_, err = writer.WriteString(str)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = writer.Flush()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
}
// Starts up a read and write thread which connect to the server through the
// a socket connection.
func main() {
wg.Add(1)
conn, err := net.Dial(CONN_TYPE, CONN_PORT)
if err != nil {
fmt.Println(err)
}
go Read(conn)
go Write(conn)
wg.Wait()
}