-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
112 lines (87 loc) · 2.43 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
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
112
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"strings"
chat_server "grpcChatServer/chat_server"
"google.golang.org/grpc"
)
func main() {
fmt.Println("Enter Server IP:Port :: [Eg: 192.168.0.1:3000]")
reader := bufio.NewReader(os.Stdin)
serverID, err := reader.ReadString('\n')
if err != nil {
log.Printf("Failed to read from console : %v ", err)
}
serverID = strings.Trim(serverID, "\r\n")
log.Printf("Connecting to %v ", serverID)
// Connect to grpc server - not using SSL/TLS encryption
conn, err := grpc.Dial(serverID, grpc.WithInsecure())
if err != nil {
log.Fatalf("Failed to connect to gRPC server : %v", err)
}
defer conn.Close()
// Call ChatService to create a stream
client := chat_server.NewServicesClient(conn)
// Passed in a context with no deadline
stream, err := client.ChatService(context.Background())
if err != nil {
log.Fatalf("Failed to call ChatService : %v", err)
}
log.Printf("%s Connected!", serverID)
// Implement communication with gRPC server
ch := clientHandle{stream: stream}
ch.clientConfig()
// init go routine to asynchronously run
go ch.sendMessage()
go ch.receiveMessage()
// Blocker channel
bl := make(chan bool)
<-bl
}
// Client handle struct
type clientHandle struct {
stream chat_server.Services_ChatServiceClient
clientName string
}
func (ch *clientHandle) clientConfig() {
// Ask username
reader := bufio.NewReader(os.Stdin)
fmt.Printf("Please insert your display name: ")
name, err := reader.ReadString('\n')
if err != nil {
log.Printf("Failed to read from console : %v ", err)
}
ch.clientName = strings.Trim(name, "\r\n")
}
// Send message
func (ch *clientHandle) sendMessage() {
for {
reader := bufio.NewReader(os.Stdin)
fmt.Printf("[User: %s ] Insert message: ", ch.clientName)
clientMessage, err := reader.ReadString('\n')
if err != nil {
log.Printf("Failed to read from console : %v ", err)
}
clientMessage = strings.Trim(clientMessage, "\r\n")
clientMessageBox := &chat_server.ClientMsg{Name: ch.clientName, Body: clientMessage}
err = ch.stream.Send(clientMessageBox)
if err != nil {
log.Printf("Error while sending message to server : %v", err)
}
}
}
// Receive message
func (ch *clientHandle) receiveMessage() {
for {
msg, err := ch.stream.Recv()
if err != nil {
log.Printf("Error in receiving message from server : %v", err)
}
// Print message to console
fmt.Printf("\n %s : %s \n", msg.Name, msg.Body)
}
}