TCP
server.go
func main() {
listen, err := net.Listen("tcp", "127.0.0.1:20000")
if err != nil {
fmt.Println("listen failed ,err", err)
return
}
for {
conn, err := listen.Accept() //建立连接
if err != nil {
fmt.Println("accept failed, err", err)
continue
}
go process(conn)
}
}
func process(conn net.Conn) {
defer conn.Close()
for {
reader := bufio.NewReader(conn)
var buf [128]byte
n, err := reader.Read(buf[:])
if err != nil {
fmt.Println("read from client failed,err", err)
break
}
recvStr := string(buf[:n])
fmt.Println("收到client端的数据:", recvStr)
conn.Write([]byte(recvStr))
}
}
client.go
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:20000")
if err != nil {
fmt.Println("err:", err)
return
}
defer conn.Close()
reader := bufio.NewReader(os.Stdin)
for true {
input, _ := reader.ReadString('\n')
inputInfo := strings.Trim(input, "\r\n")
if strings.ToUpper(inputInfo) == "Q" { // 如果输入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]))
}
}
UDP
server.go
func main() {
listen, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.ParseIP("127.0.0.1"),
Port: 30000,
Zone: "",
})
if err != nil {
fmt.Println("listen failed, err:", err)
return
}
defer listen.Close()
for true {
var data [1024]byte
n, addr, err := listen.ReadFromUDP(data[:])
if err != nil {
fmt.Println("Read udp failed, err:", err)
continue
}
fmt.Printf("data:%v addr:%v count:%v \n", string(data[:n]), addr, n)
_, err = listen.WriteToUDP(data[:n], addr)
if err != nil {
fmt.Println("write to udp failed , err:", err)
continue
}
}
}
client.go
// UDP客户端配置
func main() {
//1:连接服务器
coon, err := net.Dial("udp", "127.0.0.1:30000")
if err != nil {
fmt.Println("连接失败,err:", err)
return
}
defer coon.Close()
//发送数据
_, err = coon.Write([]byte("hello"))
if err != nil {
fmt.Println("发送信息失败,err:", err)
return
}
//接收信息
var buf [1024]byte
n, err := coon.Read(buf[:])
if err != nil {
fmt.Println("接收信息失败,err:", err)
}
fmt.Println("接收消息:", string(buf[:n]))
}