当前位置:网站首页>Implementation of TCP UDP communication with golang language

Implementation of TCP UDP communication with golang language

2022-04-23 18:36:00 Ch3n

TCP agreement

TCP/IP(Transmission Control Protocol/Internet Protocol) Transmission control protocol / Internet protocol , It's connection-oriented ( Connection oriented ) Of 、 reliable 、 Transport layer based on byte stream (Transport layer) Communication protocol , Because it's a connection oriented protocol , Data flows like water , There will be sticking problems .
Server side

/** * @Author: chentong * @Date: 2022/04/20 23:35 */

package main

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

//  Processing function 
func process(conn net.Conn) {
    
	defer conn.Close() //  Close the connection 
	for {
    
		reader := bufio.NewReader(conn)
		var buf [128]byte
		n, err := reader.Read(buf[:]) //  Reading data 
		if err != nil {
    
			fmt.Println("read from client failed, err:", err)
			break
		}
		recvStr := string(buf[:n])
		fmt.Println(" received client Data from the end :", recvStr)
		conn.Write([]byte(recvStr)) //  send data 
	}
}

func main() {
    
	listen, err := net.Listen("tcp", "127.0.0.1:8080")
	if err != nil {
    
		fmt.Println("listen failed, err:", err)
		return
	}
	for {
    
		conn, err := listen.Accept() //  Establishing a connection 
		if err != nil {
    
			fmt.Println("accept failed, err:", err)
			continue
		}
		go process(conn) //  Start a goroutine Deal with connection 
	}
}

client

/** * @Author: chentong * @Date: 2022/04/20 22:54 */

package main

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

func main() {
    
	conn, err := net.Dial("tcp", "127.0.0.1:8080")
	if err != nil {
    
		fmt.Println(err)
	}
	//  Close the connection 
	defer conn.Close()

	//  Standard output and standard error file descriptors open files 
	inputReader := bufio.NewReader(os.Stdin)
	for {
    
		input, _ := inputReader.ReadString('\n') //  Read user input 
		inputInfo := strings.Trim(input, "\r\n")
		//  If the output Q sign out 
		if strings.ToUpper(inputInfo) == "Q" {
    
			return
		}
		_, err := conn.Write([]byte(inputInfo))
		if err != nil {
    
			return
		}
		buf := [512]byte{
    }
		read, err := conn.Read(buf[:])
		if err != nil {
    
			return
		}
		fmt.Println(" receive data : ", string(buf[:read]))

	}

}

UDP agreement

UDP agreement (User Datagram Protocol) The Chinese name is user datagram protocol , yes OSI(Open System Interconnection, Open system interconnection ) A connectionless transport layer protocol in the reference model , You can send and receive data directly without establishing a connection , It's unreliable 、 Communication without timing , however UDP The real-time performance of the protocol is better , Usually used in the field of live video .

Server side

/** * @Author: chentong * @Date: 2022/04/21 10:25 */

package main

import (
	"fmt"
	"net"
)

//
// main
// @Description:  Network programming  upd  Server side 
//
func main() {
    

	// upd Address 
	updAddr := net.UDPAddr{
    
		IP:   net.IPv4(0, 0, 0, 0),
		Port: 8080,
	}
	fmt.Printf("UDP server running... IP: %v Port: %v \n", updAddr.IP, updAddr.Port)

	listen, err := net.ListenUDP("udp", &updAddr)
	if err != nil {
    
		fmt.Println("listen failed err: ", err)
		return
	}
	//  Close the connection 
	defer func(listen *net.UDPConn) {
    
		err := listen.Close()
		if err != nil {
    
			fmt.Println("listen failed err: ", err)
		}
	}(listen)
	for {
    
		//  receive data 
		var data [1024]byte
		udp, addr, err := listen.ReadFromUDP(data[:])
		if err != nil {
    
			fmt.Println("listen failed err: ", err)
			continue
		}
		fmt.Printf("data: %v add: %v count: %v \n\n", string(data[:udp]), addr, udp)
		//  send data 
		_, err = listen.WriteToUDP(data[:udp], addr)
		if err != nil {
    
			fmt.Println("listen failed err: ", err)
			continue
		}
	}

}

client

/** * @Author: chentong * @Date: 2022/04/21 10:25 */

package main

import (
	"fmt"
	"net"
)

//
// main
// @Description:  Network programming  upd  client 
//
func main() {
    

	udpAddr := net.UDPAddr{
    IP: net.IPv4(127, 0, 0, 1), Port: 8080}
	udpConn, err := net.DialUDP("udp", nil, &udpAddr)
	if err != nil {
    
		fmt.Printf(" Failed to connect to the server : %s \n", err)
		return
	}
	defer udpConn.Close()
	sendData := []byte("hello udp server")
	_, err = udpConn.Write(sendData)
	if err != nil {
    
		fmt.Printf(" Failed to send data : %s \n", err)
		return
	}
	readData := [1024]byte{
    }
	udp, addr, err := udpConn.ReadFromUDP(readData[:])
	if err != nil {
    
		fmt.Printf(" Failed to receive data : %s \n", err)
		return
	}
	fmt.Printf("recv: %v addr: %v count: %v \n", string(readData[:udp]), addr, udp)
}

版权声明
本文为[Ch3n]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231833257645.html