golang 简易tcpserver和tcpclient
golang 简易tcpserver和tcpclient
server端代码
package main
import (
"flag"
"fmt"
"net"
"strconv"
)
//Port 端口
var Port string
func main() {
fmt.Println("process start...")
flag.StringVar(&Port, "p", "", "proc port")
flag.Parse()
if Port == "" {
fmt.Print("port is null\n")
return
}
p, err := strconv.Atoi(Port)
if err != nil {
fmt.Printf("port is not number and err:[%v]\n", err)
return
}
addr := fmt.Sprintf("0.0.0.0:%d", p)
listener, err := net.Listen("tcp", addr)
if err != nil {
fmt.Printf("err! addr %s open faild err:[%v]\n", addr, err)
return
}
for {
conn, err := listener.Accept()
if err != nil {
fmt.Printf("listen err:[%v]\n", err)
}
go handConn(conn)
}
}
func handConn(conn net.Conn) {
defer func() {
fmt.Printf("client [%s] close\n", conn.RemoteAddr().String())
conn.Close()
}()
var buf [1024]byte
for {
n, err := conn.Read(buf[:])
if err != nil {
fmt.Printf("read from %s msg faild err:[%v]\n", conn.RemoteAddr().String(), err)
break
}
fmt.Printf("rev data from %s msg:%s\n", conn.RemoteAddr().String(), string(buf[:n]))
}
}
客户端代码
package main
import (
"bufio"
"flag"
"fmt"
"net"
"os"
)
var (
addr string
port int
)
func main() {
flag.StringVar(&addr, "addr", "", "server ip address")
flag.IntVar(&port, "p", 0, "server port")
flag.Parse()
if addr == "" || port == 0 {
fmt.Printf("input params error addr:[%s] port:[%d]\n", addr, port)
}
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", addr, port))
defer conn.Close()
if err != nil {
fmt.Printf("connected server [%s] faild err:%v\n", addr, err)
return
}
input := bufio.NewReader(os.Stdin)
for {
bytes, _, err := input.ReadLine()
if err != nil {
fmt.Printf("read line faild err:%v\n", err)
}
str := string(bytes)
if str == "Q" || str == "q" {
fmt.Println("exe quit!")
break
}
n, err := conn.Write(bytes)
if err != nil {
fmt.Printf("send data faild err:%v\n", err)
} else {
fmt.Printf("send data length %d\n", n)
}
}
}
不想平凡,奈何太懒 T_T