输入内容,并将输入的内容传输至网络服务端。但是目前的代码,cmd.go中的Execmd函数,从打印的日志来看,dealConn函数输入内容后会执行2次。
main.go
```go
package main
import (
"fmt"
"github.com/client/cmd"
"net"
"os"
"github.com/spf13/cobra"
)
const version = "1.0.0"
var address string
var versionFlag bool
var conn net.Conn
var RootCmd = &cobra.Command{
Use: "client",
RunE: execmd,
}
func execmd(c *cobra.Command, args []string) error {
if versionFlag {
fmt.Printf("client version %s\n", version)
return nil
}
var err error
conn, err = net.Dial("tcp", address)
if err != nil {
fmt.Println("error to connect, ", err)
return err
}
fmt.Printf("connect to %s\n", address)
return nil
}
func init() {
RootCmd.Flags().BoolVarP(&versionFlag, "version", "v", false, "show version")
RootCmd.Flags().StringVarP(&address, "addr", "d", "127.0.0.1:25610", "the host address,like 127.0.0.1:10000")
}
func main() {
defer func() {
conn.Close()
}()
if err := RootCmd.Execute(); err != nil {
os.Exit(1)
}
go cmd.Execmd(conn)
select {}
}
```
cmd.go
```go
package cmd
import (
"bufio"
"fmt"
"time"
"net"
)
func Execmd(conn net.Conn) (err error) {
time.Sleep(3 * time.Second)
var input string
for {
fmt.Printf("[%s]#", conn.RemoteAddr().String())
fmt.Scanf("%s", &input)
err = dealConn(conn,input)
if err != nil {
fmt.Printf("error to dealConn %s\n", err)
return
}
fmt.Println("return from dealConn.")
}
return nil
}
func dealConn(conn net.Conn,input string) (err error) {
fmt.Println("begin to exec cmd.")
//发送命令
conn.Write([]byte(input))
conn.Write([]byte("\n"))
//处理接受的结果
reader := bufio.NewReader(conn)
msg, err := reader.ReadString('\n')
if err != nil {
fmt.Println("response error\n")
return err
}
fmt.Println("response:", string(msg))
fmt.Println("exec cmd end.")
return nil
}
```
有疑问加站长微信联系(非本文作者)