当前位置:网站首页>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
边栏推荐
- STM32 learning record 0008 - GPIO things 1
- Cygwin64 right click to add menu, and open cygwin64 here
- Configure iptables
- 教你用简单几个步骤快速重命名文件夹名
- Function recursion and solving interesting problems
- 纠结
- 硬核解析Promise對象(這七個必會的常用API和七個關鍵問題你都了解嗎?)
- Robocode tutorial 8 - advanced robot
- Analysez l'objet promise avec le noyau dur (Connaissez - vous les sept API communes obligatoires et les sept questions clés?)
- If condition judgment in shell language
猜你喜欢

Nodejs installation

How to virtualize the video frame and background is realized in a few simple steps

ctfshow-web362(SSTI)

MATLAB从入门到精通(二)

Teach you to quickly rename folder names in a few simple steps

Excel intercept text

使用晨曦记账本,分析某个时间段每个账户收支结余

STM32: LCD显示

Jeecg boot microservice architecture

【ACM】455. 分发饼干(1. 大饼干优先喂给大胃口;2. 遍历两个数组可以只用一个for循环(用下标索引--来遍历另一个数组))
随机推荐
WIN1 remote "this may be due to credssp encryption Oracle correction" solution
Chondroitin sulfate in vitreous
Can filter
Teach you to quickly rename folder names in a few simple steps
Serial port debugging tools cutecom and minicom
Ucosiii transplantation and use, reference punctual atom
机器学习理论之(7):核函数 Kernels —— 一种帮助 SVM 实现非线性化决策边界的方式
Golang 语言实现TCP UDP通信
Daily CISSP certification common mistakes (April 13, 2022)
Quantexa CDI(场景决策智能)Syneo平台介绍
昇腾 AI 开发者创享日全国巡回首站在西安成功举行
Ionic instruction set order from creation to packaging
Robocode tutorial 8 - advanced robot
CISSP certified daily knowledge points (April 19, 2022)
CISSP certified daily knowledge points (April 14, 2022)
Tangle
[mathematical modeling] - analytic hierarchy process (AHP)
配置iptables
Resolves the interface method that allows annotation requests to be written in postman
os_ authent_ Prefix