-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
116 lines (87 loc) · 2.18 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
113
114
115
116
package main
import (
"bufio"
"context"
"fmt"
"grpcChatServer/chatserver"
"log"
"os"
"strings"
"google.golang.org/grpc"
)
func main() {
fmt.Println("Enter Server IP:Port ::: ")
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.Println("Connecting : " + serverID)
//connect to grpc server
conn, err := grpc.Dial(serverID, grpc.WithInsecure())
if err != nil {
log.Fatalf("Faile to conncet to gRPC server :: %v", err)
}
defer conn.Close()
//call ChatService to create a stream
client := chatserver.NewServicesClient(conn)
stream, err := client.ChatService(context.Background())
if err != nil {
log.Fatalf("Failed to call ChatService :: %v", err)
}
// implement communication with gRPC server
ch := clienthandle{stream: stream}
ch.clientConfig()
go ch.sendMessage()
go ch.receiveMessage()
//blocker
bl := make(chan bool)
<-bl
}
//clienthandle
type clienthandle struct {
stream chatserver.Services_ChatServiceClient
clientName string
}
func (ch *clienthandle) clientConfig() {
reader := bufio.NewReader(os.Stdin)
fmt.Printf("Your Name : ")
name, err := reader.ReadString('\n')
if err != nil {
log.Fatalf(" Failed to read from console :: %v", err)
}
ch.clientName = strings.Trim(name, "\r\n")
}
//send message
func (ch *clienthandle) sendMessage() {
// create a loop
for {
reader := bufio.NewReader(os.Stdin)
clientMessage, err := reader.ReadString('\n')
if err != nil {
log.Fatalf(" Failed to read from console :: %v", err)
}
clientMessage = strings.Trim(clientMessage, "\r\n")
clientMessageBox := &chatserver.FromClient{
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() {
//create a loop
for {
mssg, err := ch.stream.Recv()
if err != nil {
log.Printf("Error in receiving message from server :: %v", err)
}
//print message to console
fmt.Printf("%s : %s \n",mssg.Name,mssg.Body)
}
}