SoFunction
Updated on 2025-03-01

Examples of udp protocol and TCP communication implementation in go language

UDP protocol

Server side

package main
import (
	"fmt"
	"net"
)
func main() {
	// Create a listener	socket, err := ("udp4", &{
		IP:   net.IPv4(0, 0, 0, 0),
		Port: 8080,
	})
	if err != nil {
		("Supervising failed!", err)
		return
	}
	defer ()
	for {
		// Read the data transmitted from the client		data := make([]byte, 4096)
		read, remoteAddr, err := (data)
		if err != nil {
			("Reading data failed!", err)
			continue
		}
		(read, remoteAddr)
		("%s\n\n", data)
		//Send data and tell the client that it has received it		senddata := []byte("hello client!")
		_, err = (senddata, remoteAddr)
		if err != nil {
			return
			("Send data failed!", err)
		}
	}
}

Client side

package main
import (
	"fmt"
	"net"
)
func main() {
	// Create a connection	socket, err := ("udp4", nil, &{
		IP:   net.IPv4(0, 0, 0, 0),
		Port: 8080,
	})
	if err != nil {
		("The connection failed!", err)
		return
	}
	defer ()
	// Send data to the server	senddata := []byte("hello server!")
	_, err = (senddata)
	if err != nil {
		("Send data failed!", err)
		return
	}
	// Receive client data	data := make([]byte, 4096)
	read, remoteAddr, err := (data)
	if err != nil {
		("Reading data failed!", err)
		return
	}
	(read, remoteAddr)
	("%s\n", data)
}

TCP Communication (Basic)

Server side

package main
import (
	"fmt"
	"net"
)
func main() {
	//monitor	listener, err := ("tcp", "127.0.0.1:8000")
	if err != nil {
		("err = ", err)
		return
	}
	defer ()
	//Blocking and waiting for user link	conn, err := ()
	if err != nil {
		("err = ", err)
		return
	}
	//Receive user request	buf := make([]byte, 1024) // 1024 size buffer	n, err1 := (buf)
	if err1 != nil {
		("err1 = ", err1)
		return
	}
	("buf = ", string(buf[:n]))
	defer () //Close the current user link}

Client

package main
import (
	"fmt"
	"net"
)
func main() {
	//Proactively connect to the server	conn, err := ("tcp", "127.0.0.1:8000")
	if err != nil {
		("err = ", err)
		return
	}
	defer ()
	//Send data	([]byte("are u ok?"))
}

TCP communication concurrent server

Server side

package main
import (
	"fmt"
	"net"
	"strings"
)
//Process user requestfunc HandleConn(conn ) {
	//The function call is completed, the conn will be automatically closed	defer ()
	//Get the client's network address information	addr := ().String()
	(addr, " conncet sucessful")
	buf := make([]byte, 2048)
	for {
		//Read user data		n, err := (buf)
		if err != nil {
			("err = ", err)
			return
		}
		("[%s]: %s\n", addr, string(buf[:n]))
		("len = ", len(string(buf[:n])))
		//if "exit" == string(buf[:n-1]) { //nc test		if "exit" == string(buf[:n-2]) { //The client test I wrote myself, there were 2 characters extra when sending, "\r\n"			(addr, " exit")
			return
		}
		//Convert the data to uppercase and send it to the user		([]byte((string(buf[:n]))))
	}

}
func main() {
	//monitor	listener, err := ("tcp", "127.0.0.1:8000")
	if err != nil {
		("err = ", err)
		return
	}
	defer ()
	//Receive multiple users	for {
		conn, err := ()
		if err != nil {
			("err = ", err)
			return
		}
		//Process user requests and create a new coroutine		go HandleConn(conn)
	}
}

Client

package main
import (
	"fmt"
	"net"
	"os"
)
func main() {
	//Proactively connect to the server	conn, err := ("tcp", "127.0.0.1:8000")
	if err != nil {
		(" err = ", err)
		return
	}
	//The main call is completed, close the connection	defer ()
	go func() {
		//Enter content from the keyboard and send content to the server		str := make([]byte, 1024)
		for {
			n, err := (str) //Read content from the keyboard and place it in str			if err != nil {
				(". err = ", err)
				return
			}
			//Send the input content to the server			(str[:n])
		}
	}()
	//Receive data from the server reply	//Slice buffer	buf := make([]byte, 1024)
	for {
		n, err := (buf) //Receive server request		if err != nil {
			(" err = ", err)
			return
		}
		(string(buf[:n])) //Print the received content, convert it into a string and then print it	}
}

The above is the detailed content of the udp protocol and TCP communication implementation examples in the go language. For more information about the udp protocol TCP communication in the go language, please pay attention to my other related articles!