svr:
package main
import (
"fmt"
"net"
"os"
"time"
)
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
func main() {
service := ":10086"
tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
checkError(err)
fmt.Fprintf(os.Stdout, "tcpaddr : %s\n", tcpAddr.String())
listen, err := net.ListenTCP("tcp4", tcpAddr)
checkError(err)
for {
conn, err := listen.Accept()
if err != nil {
fmt.Fprintf(os.Stderr, "Accept err: ", err.Error())
continue
}
go handleTcpCli(conn)
}
defer listen.Close()
}
func handleTcpCli(conn net.Conn) {
defer conn.Close()
daytime := time.Now().String()
conn.Write([]byte(daytime))
conn.Close()
}
cli:
package main
import (
"fmt"
"io/ioutil"
"net"
"os"
)
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
func main() {
service := "127.0.0.1:10086"
if len(os.Args) != 2 {
fmt.Fprintf(os.Stdout, "Usage: %s host:port [127.0.0.1:10086]\n", os.Args[0])
} else {
fmt.Fprintf(os.Stdout, "input buf : %s\n", os.Args[1])
service = os.Args[1]
}
tcpaddr, err := net.ResolveTCPAddr("tcp4", service)
fmt.Fprintf(os.Stdout, "Address : %s\n", tcpaddr.String())
checkError(err)
conn, err := net.DialTCP("tcp", nil, tcpaddr)
checkError(err)
result, err := ioutil.ReadAll(conn)
checkError(err)
fmt.Println(string(result))
defer conn.Close()
os.Exit(0)
}
有疑问加站长微信联系(非本文作者)