当前位置:网站首页>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
边栏推荐
猜你喜欢
Résolution: cnpm: impossible de charger le fichier... Cnpm. PS1 parce que l'exécution de scripts est désactivée sur ce système
机器学习理论之(7):核函数 Kernels —— 一种帮助 SVM 实现非线性化决策边界的方式
WIN1 remote "this may be due to credssp encryption Oracle correction" solution
机器学习实战 -朴素贝叶斯
ctfshow-web361(SSTI)
机器学习理论之(8):模型集成 Ensemble Learning
Robocode tutorial 7 - Radar locking
Notepad + + replaces tabs with spaces
Promote QT default control to custom control
纠结
随机推荐
From introduction to mastery of MATLAB (2)
Daily network security certification test questions (April 12, 2022)
CISSP certified daily knowledge points (April 14, 2022)
iptables初探
Mysql database backup command -- mysqldump
【ACM】455. Distribute Biscuits (1. Give priority to big biscuits to big appetite; 2. Traverse two arrays with only one for loop (use subscript index -- to traverse another array))
ctfshow-web361(SSTI)
硬核解析Promise對象(這七個必會的常用API和七個關鍵問題你都了解嗎?)
Résolution: cnpm: impossible de charger le fichier... Cnpm. PS1 parce que l'exécution de scripts est désactivée sur ce système
STM32: LCD display
ESP32 LVGL8. 1 - label (style 14)
Promote QT default control to custom control
昇腾 AI 开发者创享日全国巡回首站在西安成功举行
Function recursion and solving interesting problems
Error reported when running tensorboard: valueerror: duplicate plugins for name projector, solution
Spark performance optimization guide
Analysez l'objet promise avec le noyau dur (Connaissez - vous les sept API communes obligatoires et les sept questions clés?)
Test post and login function
Quantexa CDI(场景决策智能)Syneo平台介绍
If condition judgment in shell language