Original link: https://grimoire.cn/golang/go-tcp.html
Preamble
As we all know, the TCP protocol is a very important part of today’s Internet. It is precisely because of the TCP protocol that data can be transmitted between devices without errors.
The latest http3 protocol has abandoned the tcp method and instead uses udp + quic to realize data transmission
Let’s talk about some basics of TCP/IP:
- TCP is a protocol of the transport layer and is implemented on top of IP (network layer). This protocol is generally implemented at the operating system level.
- The TCP protocol is connection-oriented and provides reliable delivery (data transmission will not be lost, the content sent by the sender and the content received by the receiver are consistent)
Code
Server
Before implementing, let’s talk about the idea:
- Because tcp is connection-oriented, we should first try to establish a connection. We don’t need to control the establishment process. The operating system has already helped us achieve it.
- Then, we need to have an independent coroutine responsible for handling this connection and listening for the data sent by the connection
According to this idea, we simply implement:
/* * @Author: NorthCity1984 * @LastEditTime: 2022-10-18 23:47:00 * @Description * @Website: https://grimoire.cn * Copyright (c) NorthCity1984 All rights reserved. */ package main import ( "log" "net" ) /**负责处理一个连接,监听并打印*/ func accept(conn net.Conn) { defer conn.Close() for { buffer := [256]byte{} n, err := conn.Read(buffer[:]) if err != nil { log.Println(err) break } log.Println("message: ", string(buffer[:n])) } } func main() { // 启动一个tcp server, 在3000 端口监听listen, err := net.Listen("tcp", ":3000") if err != nil { log.Fatal(err) } defer listen.Close() for { // 等待连接,在没有连接的时候,主进程会在这里阻塞, // 直到有client 请求连接conn, err := listen.Accept() if err != nil { log.Println(err) break } log.Println("accept from:", conn.RemoteAddr()) // 启动一个goroutine 处理这个连接go accept(conn) } }
client
The client is simpler than the server, because it does not need to deal with multiple servers, then the client only needs one tcp. Let’s simply write
/* * @Author: NorthCity1984 * @LastEditTime: 2022-10-18 23:53:41 * @Description: * @Website: https://grimoire.cn * Copyright (c) NorthCity1984 All rights reserved. */ package main import ( "fmt" "log" "net" ) func main() { // 创建一个tcp 客户端conn, err := net.Dial("tcp", ":3000") if err != nil { log.Panicln(err) } defer conn.Close() for { var input string fmt.Scan(&input) _, err := conn.Write([]byte(input)) // 写入tcp 连接中if err != nil { log.Println(err) break } } }
Tips
Because tcp actually transmits bytes, you can even use some clients that are also tcp protocol to request this service port, such as ssh, although it can’t be connected (le
This article is reproduced from: https://grimoire.cn/golang/go-tcp.html
This site is for inclusion only, and the copyright belongs to the original author.