I'm trying to execute a program remote via a tcp connection and I want to share the stdout and stdin live between client<>server.
I've the following test server without error handling :p I know, at the moment I'm not able to execute a program with arguments, but that's easy to handle :)
package main
import (
"bufio"
"bytes"
"fmt"
"net"
"os/exec"
"strings"
)
func main() {
l, _ := net.Listen("tcp", ":420")
defer l.Close()
for {
// Wait for a connection.
conn, _ := l.Accept()
go func(c net.Conn) {
for {
msg, _ := bufio.NewReader(conn).ReadString('
')
program := strings.Trim(msg, "
")
cmd := exec.Command(program)
var b bytes.Buffer
cmd.Stdout = &b
//cmd.Stdin = &bi
cmd.Run()
c.Write([]byte(b.String() + "
")) //not working
fmt.Println(b.String()) //working
}
//connection closed
c.Close()
}(conn)
}
}
You see, I try to share the stdout with c.Write(), but this won't work.
The other problem with cmd.Stdin will be the same problem as Stdout, I think. At this moment I didn't implement any Stdin-functions.
Could anybody give me a tip or example code for this function?
You can try this one
package main
import (
"bufio"
"bytes"
"fmt"
"net"
"os/exec"
"strings"
)
func main() {
l, _ := net.Listen("tcp", ":8888")
defer l.Close()
for {
// Wait for a connection.
conn, _ := l.Accept()
go func(c net.Conn) {
for {
msg, err := bufio.NewReader(conn).ReadString('
')
if err != nil {
break
}
program := strings.Trim(msg, "
")
cmd := exec.Command(program)
var b bytes.Buffer
cmd.Stdout = &b
cmd.Run()
conn.Write(b.Bytes())
}
//connection closed
c.Close()
}(conn)
}
}
client
package main
import (
"fmt"
"net"
)
func main() {
conn, _ := net.Dial("tcp", "127.0.0.1:8888")
for {
fmt.Print("Command to send: ")
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('
')
conn.Write([]byte(fmt.Sprintf("%s
", text)))
b := make([]byte, 512)
conn.Read(b)
fmt.Println(string(b))
}
}