当前位置:网站首页>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
边栏推荐
- Usage of functions decode() and replace() in SQL
- CISSP certified daily knowledge points (April 14, 2022)
- QT add external font ttf
- Chondroitin sulfate in vitreous
- Permission management with binary
- ESP32 LVGL8. 1 - BTN button (BTN 15)
- Matlab tips (6) comparison of seven filtering methods
- CISSP certified daily knowledge points (April 18, 2022)
- iptables初探
- Feign requests the log to be printed uniformly
猜你喜欢
ctfshow-web362(SSTI)
机器学习理论之(7):核函数 Kernels —— 一种帮助 SVM 实现非线性化决策边界的方式
Teach you to quickly rename folder names in a few simple steps
With the use of qchart, the final UI interface can be realized. The control of qweight can be added and promoted to a user-defined class. Only the class needs to be promoted to realize the coordinate
Promote QT default control to custom control
Matlab tips (6) comparison of seven filtering methods
Function recursion and solving interesting problems
纠结
iptables初探
Hard core parsing promise object (do you know these seven common APIs and seven key questions?)
随机推荐
Stm32mp157 wm8960 audio driver debugging notes
ctfshow-web362(SSTI)
特征选择feature_selection--SelectKBest
【ACM】376. Swing sequence
Daily CISSP certification common mistakes (April 14, 2022)
STM32: LCD display
In shell programming, the shell file with relative path is referenced
关于unity文件读取的操作(一)
Analysez l'objet promise avec le noyau dur (Connaissez - vous les sept API communes obligatoires et les sept questions clés?)
ESP32 LVGL8. 1 - event (event 17)
os_ authent_ Prefix
kettle庖丁解牛第17篇之文本文件输出
Daily network security certification test questions (April 15, 2022)
Keil RVMDK compiled data type
七、DOM(下) - 章节课后练习题及答案
机器学习实战 -朴素贝叶斯
Golang 语言实现TCP UDP通信
Multifunctional toolbox wechat applet source code
Spark performance optimization guide
Use Chenxi bookkeeping book to analyze the balance of revenue and expenditure of each account in a certain period of time