1. 程式人生 > >Go語言實現UDP併發傳輸

Go語言實現UDP併發傳輸

Server

addr,err:=net.ResolveUDPAddr("udp","127.0.0.1:8006")
	if err!=nil {
		fmt.Print(err)
		return
	}
	listener,err:=net.ListenUDP("udp",addr)
	if err!=nil {
		fmt.Print(err)
		return
	}
	defer listener.Close()
	buf:=make([]byte,1024)
	for  {
		n,ctlAddr,err:=listener.ReadFromUDP(buf)
		if err!=nil {
			fmt.Print(err)
			continue
		}
		go func() {
			_,err=listener.WriteToUDP([]byte(strings.ToUpper(string(buf[:n]))),ctlAddr)
			if err!=nil {
				fmt.Print(err)
				return
			}
		}()
	}

Client

conn,err:=net.Dial("udp","127.0.0.1:8006")
	if err!=nil {
		fmt.Print(err)
		return
	}
	defer conn.Close()
	go func() {
		buf:=make([]byte,1024)
		for  {
			n,err:=os.Stdin.Read(buf)
			if err!=nil {
				fmt.Print(err)
				continue
			}
			conn.Write(buf[:n])
		}
	}()
	buf:=make([]byte,1024)
	for  {
		n,err:=conn.Read(buf)
		if err!=nil {
			fmt.Print(err)
			continue
		}
		fmt.Print(string(buf[:n]))
	}