-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
96 lines (87 loc) · 1.78 KB
/
client.go
File metadata and controls
96 lines (87 loc) · 1.78 KB
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
package main
import (
"bufio"
"fmt"
"goplay/message"
"log"
"net"
"os"
)
func client() {
conn, err := net.Dial("tcp", serverIp+serverPort)
if err != nil {
log.Fatalln(err)
}
name := MakeName()
chat(name, conn)
}
func MakeName() string {
hn, _ := os.Hostname()
ipSlice, _ := net.LookupIP(hn)
// find ipv4 addr in ipSlice
ipv4 := func() string {
for i := range ipSlice {
for j := range ipSlice[i] {
if ipSlice[i][j] == byte('.') {
return ipSlice[i].String()
}
}
}
return ""
}()
pid := os.Getpid()
return ipv4 + fmt.Sprint(pid)
}
func chat(name string, conn net.Conn) {
input := bufio.NewScanner(os.Stdin)
fmt.Printf("Your name(default %s): ", name)
input.Scan()
if buf := input.Text(); buf != "" {
name = buf
}
fmt.Printf("login %s%s using name: %s\n", serverIp, serverPort, name)
fmt.Printf("Peer's name: ")
input.Scan()
peer := input.Text()
fmt.Printf("Chat with peer: %s\n", peer)
var connCh chan []byte = make(chan []byte)
var inputCh chan []byte = make(chan []byte)
go func() {
for {
var data []byte = make([]byte, MAXINPUT)
n, err := conn.Read(data)
if err != nil {
close(connCh)
log.Fatal(err)
} else {
connCh <- data[:n]
}
}
}()
go func() {
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
inputCh <- []byte(input.Text())
}
}()
sendMsg := message.SendMsg{
Name: name,
TargetName: peer,
}
conn.Write(sendMsg.Encode())
for {
var receiveMsg message.ReceiveMsg
select {
case sendMsg.Body = <-inputCh:
data := sendMsg.Encode()
_, err := conn.Write(data)
if err != nil {
log.Fatalln(err)
}
case receiveData := <-connCh:
receiveMsg.Decode(receiveData)
buf := fmt.Sprintf("%s: %s", receiveMsg.SourceName, string(receiveMsg.Body))
fmt.Println(buf)
}
}
}