go语言网络编程——UDP编程

服务器端:

package main

import (
	"fmt"
	"net"
)

func main() {
	fmt.Println("UDP Server is listening……")
	listen, err := net.ListenUDP("udp", &net.UDPAddr{
		IP: net.IPv4(0, 0 , 0, 0),
		Port: 30000,
	})
	if err != nil {
		fmt.Println("listen failed, err:", err)
		return
	}
	defer listen.Close()
	for {
		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
		}
	}
}

客户端:

package main

import (
	"fmt"
	"net"
	"bufio"
	"os"
)

func main() {
	socket, err := net.DialUDP("udp", nil, &net.UDPAddr{
		IP: net.IPv4(0, 0, 0, 0),
		Port: 30000,
	})
	if err != nil {
		fmt.Println("连接服务器失败,err:", err)
		return
	}
	defer socket.Close()
	fmt.Println(">>")
	inputReader := bufio.NewReader(os.Stdin)
	sendData, _ := inputReader.ReadString('\n')
	_, err = socket.Write([]byte(sendData))
	if err != nil {
		fmt.Println("发送数据失败, err:",err)
		return
	}
	data := make([]byte, 4096)
	n, remoteAddr, err := socket.ReadFromUDP(data)
	if err != nil {
		fmt.Println("接收数据失败, err:", err)
		return
	}
	fmt.Printf("recv:%v addr:%v count:%v\n", string(data[:n]), remoteAddr, n)
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页