current position:Home>[golang] walk into go language lesson 24 TCP high-level operation
[golang] walk into go language lesson 24 TCP high-level operation
2021-08-25 18:49:37 【I'm Xiaobai】
【Golang】️ Walk into Go Language ️ Lesson 24 TCP High order operation
summary
Golang Is a new cross platform programming language . Today, Xiaobai will take you hand in hand into Golang The world of . ( The first 24 course )
Basic knowledge of
Conn Interface
Conn It is a general stream oriented network connection . Multiple Goroutine Can call at the same time Conn The method on the .
net.Listen()
Monitor local network broadcasts .
Format :
net.Listen(network, address string)
Parameters :
- network: Network mode , “tcp”, “tcp4”, “tcp6”, “unix”, “unixpacket” One out of six
- address: network address
Example :
listen_socket, err := net.Listen("tcp", "127.0.0.1:8888")
Return value :
- listen_socket: Listening interface
- err: error
listener.Accept()
Connect to the client .
Format :
listener.Accept()
Example :
conn, err := listen_socket.Accept()
Return value :
- conn: Network interface
- err: error
conn.Read()
Read information .
Format :
conn.Read(b []byte)
Example :
nums, err := conn.Read(buffer)
Return value :
- nums: Number of bytes read
- err: error
conn.Write()
Transmit information .
Format :
conn.Write(b []byte)
Example :
conn.Write([]byte("Hi, Server"))
Interactive communication
The server
package main
import (
"fmt"
"net"
)
// Send a message
func send_info(conn net.Conn) {
// Send a message
_, err := conn.Write([]byte("Message received"))
error_check(err)
fmt.Println(" Send a message : Message received")
}
// receive messages
func receive_info(conn net.Conn) {
// buffer
buffer := make([]byte, 1024)
// Cyclic reading
for {
// Reading data
nums, err := conn.Read(buffer)
if err != nil {
break
}
if nums != 0 {
// Get address
address := conn.RemoteAddr()
fmt.Println(" Received a message :", string(buffer[:nums]), " come from :", address)
}
// Send a message
send_info(conn)
}
}
// Error handling
func error_check(err error) {
if err != nil {
fmt.Println("Error:", err)
}
}
func main() {
fmt.Println(" The server is starting ...")
// establish TCP Server side
listen_socket, err := net.Listen("tcp", "127.0.0.1:8888")
error_check(err)
// close
defer listen_socket.Close()
fmt.Println(" The server is started , Waiting for the connection ...")
// Start the connection
for {
// Connect new client
conn, err := listen_socket.Accept()
error_check(err)
// Receive every client
go receive_info(conn)
}
}
client
package main
import (
"bufio"
"fmt"
"net"
"os"
)
// Send a message
func send_msg(conn net.Conn) {
// Cycle to send
for {
// Read keyboard input
reader := bufio.NewReader(os.Stdin)
// Read a line
data, _, _ := reader.ReadLine()
// received exit, Close client
if string(data) == "exit" {
fmt.Println(" Client shutdown ")
break
}
// Send the input string
_, err := conn.Write(data)
if err != nil {
conn.Close()
fmt.Println("Error:", err, " Client shutdown ")
break
}
}
}
func main() {
fmt.Println(" The customer service side is establishing a connection ...")
// Set up a network connection
conn, err := net.Dial("tcp", "127.0.0.1:8888")
if err != nil {
fmt.Println(" Network connection error ")
os.Exit(1)
}
fmt.Println(" The client successfully connected to the server , Server address :", conn.RemoteAddr())
// Send a message
go send_msg(conn)
// receive messages
buffer := make([]byte, 1024)
// Cyclic reception
for {
// Read message
nums, err := conn.Read(buffer)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Println(" Received a message :", string(buffer[:nums]))
}
}
Output results :
Server side :
The server is starting ...
The server is started , Waiting for the connection ...
Received a message : hole 1 hole 1, I'm a hole 2 come from : 127.0.0.1:62831
Send a message : Message received
Received a message : hole 1 hole 1, I'm a hole 3 come from : 127.0.0.1:55002
Send a message : Message received
client :
The customer service side is establishing a connection ...
The client successfully connected to the server , Server address : 127.0.0.1:8888
hole 1 hole 1, I'm a hole 3
Received a message : Message received
copyright notice
author[I'm Xiaobai],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210825184934304Y.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
- Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
- Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
- August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
guess what you like
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
-
Introduction to flex flexible layout in CSS -- learning notes
-
CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
-
Today, let's talk about the arrow function of ES6
-
Some thoughts on small program development
-
Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
-
Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
-
Asynchronous solution async await
-
Analysis and expansion of Vue infinite scroll source code
Random recommended
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich