服务端
func TcpListen(address string) {
fmt.Println("tcp监听")
listen, err := net.Listen("tcp", address)
if err != nil {
fmt.Errorf("tcp%s监听失败=>%#v", address, err)
return
}
for {
conn, err := listen.Accept()
if err != nil {
fmt.Errorf("建立连接失败=>%#v", err)
continue
}
go netWorkHandler.Process(conn)
}
}
func Process(conn net.Conn) {
fmt.Println("----获取到新消息--执行-")
defer conn.Close()
for {
reader := bufio.NewReader(conn)
var buf [1024]byte
n, err := reader.Read(buf[:])
if err != nil {
break
}
recvStr := string(buf[:n])
fmt.Println("收到客户端的数据:", recvStr)
conn.Write([]byte(recvStr))
}
}
func main() {
go listener.TcpListen("0.0.0.0:20001")
select {}
}
客户端
可以再控制台输入来测试
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func MakeTcpConn(address string) {
conn, err := net.Dial("tcp", address)
if err != nil {
fmt.Println("err :", err)
return
}
defer conn.Close()
inputReader := bufio.NewReader(os.Stdin)
for {
input, _ := inputReader.ReadString('\n')
inputInfo := strings.Trim(input, "\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]))
}
}
|