• go语言之UDP通信


    服务端

    package main
    
    import (
    	"fmt"
    	"net"
    )
    
    func main() {
    	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"
    )
    
    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()
    	sendData := []byte("Hello server")
    	_, err = socket.Write(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)
    }
    

      

  • 相关阅读:
    node(3)MVC代码结构模式moogoDB的学习
    node(2)
    node (1)
    函数上下文的判断
    JSON解析
    原生ajax
    new 关键字
    String 截取字符串#中间的文本
    WARN警告:Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended
    在Java8的foreach()中使用break、continue
  • 原文地址:https://www.cnblogs.com/mango1997/p/16058694.html
Copyright © 2020-2023  润新知