当前位置:网站首页>Golang -- TCP implements concurrency (server and client)
Golang -- TCP implements concurrency (server and client)
2022-07-06 04:55:00 【Java mage】
Server End common function 、 Interface :
Listen function :
func Listen(network, address string) (Listener, error)
network: Optional Protocol :TCP、UDP, Such as :“tcp” or “udp”
address:IP Address + Port number , Such as :“127.0.0.1:8000” or “:8000”
Listener Interface :
type Listener interface {
Accept() (Conn, error)
Close() error
Addr() Addr
}
Conn Interface :
type Conn interface {
Read(b []byte) (n int, err error)
Write(b []byte) (n int, err error)
Close() error
LocalAddr() Addr
RemoteAddr() Addr
SetDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
SetWriteDeadline(t time.Time) error
}
TCP- Server implementation :
func main() {
// Specify the communication protocol of the server 、ip、 port ,Listen Do not monitor by itself , This step is to create a for listening Socket
listen, err := net.Listen("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("net.Listen error :", err)
return
}
defer listen.Close()
fmt.Println(" The server is up , Wait for the client to connect ")
// Block listening for client connection requests , After the connection is successfully established, the... For communication will be returned Socket
accept, err := listen.Accept()
if err != nil {
fmt.Println("listen.Accept error :", err)
return
}
defer accept.Close()
fmt.Println(" The connection between the server and the client was successful ")
// Read the request initiated by the client
buf := make([]byte, 4096)
read, err := accept.Read(buf)
if err != nil {
fmt.Println("accept.Read error :", err)
return
}
// Process data after receiving data
fmt.Println(" Server get to :", string(buf[:read]))
}
Mac Can pass netcat To test :

TCP- Client implementation :
Server side :
func main() {
// Specify the communication protocol of the server 、ip、 port ,Listen Do not monitor by itself , This step is to create a for listening Socket
listen, err := net.Listen("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("net.Listen error :", err)
return
}
defer listen.Close()
fmt.Println(" The server is up , Wait for the client to connect ")
// Block listening for client connection requests , After the connection is successfully established, the... For communication will be returned Socket
accept, err := listen.Accept()
if err != nil {
fmt.Println("listen.Accept error :", err)
return
}
defer accept.Close()
fmt.Println(" The connection between the server and the client was successful ")
// Read the request initiated by the client
buf := make([]byte, 4096)
read, err := accept.Read(buf)
if err != nil {
fmt.Println("accept.Read error :", err)
return
}
accept.Write(buf[:read]) // Read the data and write it back
// Process data after receiving data
fmt.Println(" Server get to :", string(buf[:read]))
}
client :
func main() {
// Specify the communication protocol of the client 、ip、 port ,Listen Do not monitor by itself , This step is to create a for listening Socket
dial, err := net.Dial("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("net.Dial error :", err)
return
}
defer dial.Close()
// send data
dial.Write([]byte(" I'm the client "))
// Receive the data returned by the server
buf := make([]byte, 4096)
read, err := dial.Read(buf)
if err != nil {
fmt.Println("accept.Read error :", err)
return
}
// Process data after receiving data
fmt.Println(" The client gets :", string(buf[:read]))
}
TCP Implement concurrency - The server :
The above is the client communication of the stand-alone version , If you want to achieve concurrency , Need to use Goroutine+ Cycle to achieve
- Loop read data sent by client
- If the client forcibly closes the connection, it needs to be handled
- The client sends exit when
demonstration :
package main
import (
"fmt"
"net"
"strings"
)
func main() {
// Create a listening socket
listen, err := net.Listen("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("net.Listen error :", err)
return
}
defer listen.Close()
// Create client connection request
fmt.Println(" Server started successfully , Wait for the client to connect !")
for {
accept, err := listen.Accept()
if err != nil {
fmt.Println("listen.Accept error :", err)
return
}
// Call the function that the server communicates with the client
go HandlerConnect(accept)
}
}
func HandlerConnect(accept net.Conn) {
defer accept.Close()
// Get the data sent by the client
// Get the network address of the connected client
addr := accept.RemoteAddr()
fmt.Println(addr, " Client connection successful !")
buf := make([]byte, 4096)
for {
read, err := accept.Read(buf)
if err != nil {
fmt.Println("accept.Read error :", err)
return
}
fmt.Println(" The server reads data :", string(buf[:read]))
// After the simulation server receives the data , Send back to the client , Small to capital
data := strings.ToUpper(string(buf[:read]))
accept.Write([]byte(data))
}
}

TCP Implement concurrency - client :
demonstration :
package main
import (
"fmt"
"net"
"os"
)
func main() {
// Send connection request actively
dial, err := net.Dial("tcp", "127.0.0.1:8000")
if err != nil {
fmt.Println("et.Dial Something went wrong ", err)
return
}
defer dial.Close()
// os.Stdin(): Get user keyboard entry ,
go func() {
str := make([]byte, 4096)
for {
read, err := os.Stdin.Read(str)
if err != nil {
fmt.Println("os.Stdin.Read Something went wrong ", err)
continue
}
// The read data is written to the server , Read as much as you write
dial.Write(str[:read])
}
}()
buf := make([]byte, 4096)
// Echo the data sent by the server , Capitalize
for {
read, err := dial.Read(buf)
// read=0 Description of the opposite end close connection , If you close the connection, there is no need to read data down here
if read == 0 {
fmt.Println(" It is detected that the server has been disconnected !")
return
}
if err != nil {
fmt.Println(" Echo the data sent by the server dial.Read Something went wrong ", err)
return
}
fmt.Println(" The client reads the echo data of the server ", string(buf[:read]))
}
}

边栏推荐
- Complete list of common functions of turtle module
- Drive development - the first helloddk
- 程序员在互联网行业的地位 | 每日趣闻
- The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
- Basic knowledge and examples of binary tree
- Use sentinel to interface locally
- Three.js学习-光照和阴影(了解向)
- [try to hack] John hash cracking tool
- Distributed transaction solution
- Postman测试报告
猜你喜欢

Yolov5 tensorrt acceleration

RT thread analysis log system RT_ Kprintf analysis

IPv6 comprehensive experiment

麥斯克電子IPO被終止:曾擬募資8億 河南資產是股東

Basic knowledge and examples of binary tree

你需要知道的 TCP 三次握手

Delete subsequence < daily question >

Programmers' position in the Internet industry | daily anecdotes
![[lgr-109] Luogu may race II & windy round 6](/img/fe/d5b67c7dff759c519a04da023630ea.png)
[lgr-109] Luogu may race II & windy round 6

Principle and performance analysis of lepton lossless compression
随机推荐
Canal synchronizes MySQL data changes to Kafka (CentOS deployment)
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
力扣(LeetCode)186. 翻转字符串里的单词 II(2022.07.05)
也算是學習中的小總結
Luogu deep foundation part 1 Introduction to language Chapter 2 sequential structure programming
Complete list of common functions of turtle module
A blog to achieve embedded entry
Extension of graph theory
Selection sort
Fuzzy -- basic application method of AFL
Scala function advanced
Request (request object) and response (response object)
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
MySQL reported an error datetime (0) null
Summary of three log knowledge points of MySQL
ue5 小知识 FreezeRendering 查看视锥内渲染的物体
Postman pre script - global variables and environment variables
2021RoboCom机器人开发者大赛(初赛)
關於Unity Inspector上的一些常用技巧,一般用於編輯器擴展或者其他
Flody的应用