当前位置:网站首页>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
边栏推荐
- Using transmittablethreadlocal to realize parameter cross thread transmission
- Introduction to quantexa CDI syneo platform
- ctfshow-web362(SSTI)
- Custom prompt box MessageBox in QT
- Daily network security certification test questions (April 12, 2022)
- QT excel operation summary
- 数据库上机实验四(数据完整性与存储过程)
- The vivado project corresponding to the board is generated by TCL script
- Test post and login function
- The first leg of the national tour of shengteng AI developer creation and enjoyment day was successfully held in Xi'an
猜你喜欢

ctfshow-web361(SSTI)

ctfshow-web361(SSTI)

实战业务优化方案总结---主目录---持续更新

【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))

os_ authent_ Prefix

ctfshow-web362(SSTI)

多功能工具箱微信小程序源码

Jeecg boot microservice architecture

On iptables

Differences between SSD hard disk SATA interface and m.2 interface (detailed summary)
随机推荐
Software test summary
Daily network security certification test questions (April 14, 2022)
ESP32 LVGL8. 1 - label (style 14)
Jeecg boot microservice architecture
Keil RVMDK compiled data type
硬核解析Promise對象(這七個必會的常用API和七個關鍵問題你都了解嗎?)
Hard core parsing promise object (do you know these seven common APIs and seven key questions?)
Const keyword, variable and function are decorated with const
使用晨曦记账本,分析某个时间段每个账户收支结余
22年字节跳动飞书人力套件三面面经
Stm32mp157 wm8960 audio driver debugging notes
Mysql database backup command -- mysqldump
特征选择feature_selection--SelectKBest
【ACM】455. 分发饼干(1. 大饼干优先喂给大胃口;2. 遍历两个数组可以只用一个for循环(用下标索引--来遍历另一个数组))
实战业务优化方案总结---主目录---持续更新
Domestic GD chip can filter
机器学习理论基础篇--关于机器学习的一些术语
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
CISSP certified daily knowledge points (April 15, 2022)
Resolves the interface method that allows annotation requests to be written in postman