Go programming language --- based on UDP Socket

Go language - based on UDP Socket Programming

Blog Description

Information in the article involved from the Internet and organize personal conclusion, meaning that the individual learning experience and summary, what if infringement, please contact me to delete, thank you!

UDP Introduction

UDP protocol (User Datagram Protocol) is the Chinese name of the User Datagram Protocol, is the OSI (Open System Interconnection, Open Systems Interconnection) reference model of one connectionless transport layer protocol, without establishing a connection and data can be transmitted directly reception, are unreliable, no communication timing, but the real-time UDP protocol is better, generally used for live video related fields.

Service-side implementation

package main

import (
	"fmt"
	"net"
)

func main(){
	//监听udp
	listen,err := net.ListenUDP("udp",&net.UDPAddr{
		IP:net.IPv4(0,0,0,0),
		Port: 1021,
	})
	if err != nil {
		fmt.Println("监听失败,err:",err)
		return
	}

	//关闭连接
	defer listen.Close()

	for {
		var data [1024]byte
		//读取
		n, addr ,err := listen.ReadFromUDP(data[:])
		if err != nil{
			fmt.Println("读取失败,err:",err)
			continue
		}
		fmt.Printf("接收的内容是:%v,来自地址:%v,字节数量:%v\n",string(data[:n]), addr, n)
		//发送数据
		_, err  = listen.WriteToUDP(data[:n],addr)
		if err != nil{
			fmt.Println("发送失败,err:",err)
			continue
		}
	}

}

Client implementation

package main

import (
	"fmt"
	"net"
)

func main(){
	socket, err := net.DialUDP("udp",nil,&net.UDPAddr{
		IP:  net.IPv4(0,0,0,0) ,
		Port: 1021,
	})
	if err != nil{
		fmt.Println("连接失败,err:",err)
		return
	}

	defer socket.Close();

	sendData := []byte("你好,服务器")
	//发送数据
	_, 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("发送的信息:%v,目标地址:%v,字节数量:%v\n",string(data[:n]),remoteAddr,n)
}

Compile the test

Using goland

First run the server, and then run the client

Here Insert Picture Description

Run the client to send messages by default

Here Insert Picture Description

Server receives

Here Insert Picture Description

thank

Universal Network

And a hardworking own

He published 199 original articles · won praise 531 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_45163122/article/details/105119435