Reputation: 11
I am attempting to implement a command line interface that will send a string over tcp,and a handler that will modify that string and send back the result. So far, I can get the message to send and I can modify it, but any following messages are not processed. How should I improve this code to handle multiple strings/messages?
//client
package main
import (
"fmt"
"net"
"bufio"
"os"
"strings"
)
func main () {
fmt.Println("initializing sender...")
testShell()
}
func testShell() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Stirring the GRAT...")
fmt.Println("GRAT Stirred!")
for {
clInput, _ := reader.ReadString('\n')
convert := strings.Replace(clInput, "\n", "", -1)
sendMessage(convert)
//listener()
}
}
func sendMessage (input string) {
conn, err := net.Dial("tcp", "127.0.0.1:8080")
if err != nil {
fmt.Println(err)
}
message := []byte(input)
conn.Write(message)
conn.Close()
getter()
}
func getter() {
listener, err := net.Listen("tcp", "127.0.0.1:9090")
//defer listener.Close()
if err != nil {
fmt.Println(err)
}
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
}
for i := 0; i < 1; i++ {
incoming, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Println(incoming)
}
}
}
______________________________________________________________________________
//server
package main
import (
"fmt"
"net"
//"strings"
"bufio"
)
func main() {
fmt.Println("initializing relay...")
receiver()
}
func receiver() {
listener, err := net.Listen("tcp", "127.0.0.1:8080")
//defer listener.Close()
if err != nil {
fmt.Println(err)
}
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
}
for i := 0; i < 1; i++ {
incoming, _ := bufio.NewReader(conn).ReadString('\n')
//if err != nil {
//fmt.Println(err)
//}
fmt.Println(incoming)
incoming = "modified " + incoming
sendMessage(incoming)
i += 1
}
}
}
func sendMessage(input string) {
conn, err := net.Dial("tcp", "127.0.0.1:9090")
if err != nil {
fmt.Println(err)
}
message := []byte(input)
conn.Write(message)
conn.Close()
}
Upvotes: 1
Views: 73
Reputation: 51622
Your code executes only once because the listeners on both sides never terminate. That is not the only problem with the code.
First: why two connections? You can send the response back to the same connection once you accept it. You need to have a mechanism to let the other side know when the message ends, and \n
is a way of doing that however you seem to be removing it from your strings.
Second: on the sender side, after you send your message you start a listener, and enter into a for loop that accepts connections. That for loop never terminates, so after processing the first message, there is no way to send a second one.
My suggestion would be to first change your program to use one tcp connection to which both ends write to and from which both ends read from. Then you can read the input, send data, process it, and receive it many times until one side closes the connection.
Upvotes: 1