一、server端
package main
import (
"bufio"
"fmt"
"net"
)
func main() {
listen, err := net.Listen("tcp", "192.168.0.113: 20000")
if err != nil {
fmt.Println("listen failed, err: ", err)
return
}
for {
connect, err := listen.Accept()
if err != nil {
fmt.Println("accept failed err: ", err)
continue
}
go process(connect)
}
}
func process(connect net.Conn) {
defer connect.Close()
for {
reader := bufio.NewReader(connect)
var buf [128]byte
n, err := reader.Read(buf[:])
if err != nil {
fmt.Println("read from client failed , err : ", err)
break
}
recvStr := "form server: " + string(buf[:n])
fmt.Println("收到client端发来的数据: ", recvStr)
connect.Write([]byte(recvStr))
}
}
二 client
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
conn, err := net.Dial("tcp", "192.168.0.113: 20000")
if err != nil {
fmt.Println("err: ", err)
return
}
defer conn.Close()
inputReader := bufio.NewReader(os.Stdin)
for {
intput, _ := inputReader.ReadString('\n')
inputInfo := strings.Trim(intput, "\r\n")
if strings.ToUpper(inputInfo) == "Q" {
return
}
_, err := conn.Write([]byte(inputInfo))
if err != nil {
return
}
buf := [512]byte{}
n, err := conn.Read(buf[:])
if err != nil {
fmt.Println("recv failed, err: ", err)
return
}
fmt.Println(string(buf[:n]))
}
}
网友评论