I have to write a client side code that is receiving messages in the form of strings from server as well as taking input from the console to end message to the server. Both these operations should run concurrently with each other. I have written a code which perform these operations but sequentially not concurrently.
Here's what my current code looks like:
func SocketClient() {
conn, err := net.Dial("tcp", ":9000")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
server_reader := bufio.NewReader(conn)
input_reader := bufio.NewReader(os.Stdin)
for {
// for sending messages
buff, err := input_reader.ReadString('
')
if err != nil {
log.Fatalln(err)
}
conn.Write([]byte(buff))
// for receiving messages but this won't run until the above has taken input from console
buff2, err := server_reader.ReadString('
')
if err != nil {
log.Fatalln(err)
}
fmt.Println("Received: %s", buff2)
}
}
buff receives incoming messages from server and then buff2 takes outgoing message input from console but in order to receive the incoming messages again, buff2 needs some input. I know this can be done using channels, mutex locks etc. but because of my lack of understanding of fundamentals I am having problem using them.
I guess the actual code should look something like this:
func SocketClient() {
conn, err := net.Dial("tcp", ":9000")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
go func() {
// for sending messages
} ()
go func() {
// for receiving messages
} ()
}
How to make the input and output as two separate goroutines?