Go language foundation-a simple TCP programming

TCP programming in Go language has the same structural order as many other programming languages, but there are differences in syntax

TCP/IP protocol

The TCP/IP protocol, that is, the Transmission Control Protocol/Internet Protocol, is a connection-oriented, reliable, byte stream-based transport layer communication protocol. The unit of transmission is message segment, because it is a connection-oriented protocol There will be sticky bags.

TCP programming server

As in Java programming, the server of Go language can also connect to multiple clients, and the order of execution is roughly the same. (All follow the TCP/IP protocol, it must be the same, here is nonsense)

  • The workflow of the server in the Go language:
  • (1) Listening port, waiting to be connected
  • (2) Receive the connection request from the client
  • (3). Create goroutine to handle links. (This is the difference from the Java language. Java is mostly processed by one thread)

GoroutineIt is a lightweight abstraction built on threads. It allows us to execute multiple functions or methods in parallel in the same address space at a very low cost. Compared with threads, its creation and destruction costs are much smaller, and its scheduling is independent of threads. Creating a goroutine in golang is very simple, just use the "go" keyword.

Server code

import (
	"bufio"
     "fmt"
	 "net"
)
//TCP server端
func process(conn net.Conn) {
    
    
	defer conn.Close() // 关闭连接
	for {
    
    
		reader := bufio.NewReader(conn)
		var buf [128]byte
		n, err := reader.Read(buf[:]) // 读取数据
		if err != nil {
    
    
		//如果有错误信息,就打印错误信息
			fmt.Println("read from client failed, err:", err)
			break
		}
		recvStr := string(buf[:n])
		fmt.Println("收到client端发来的数据:", recvStr)
		conn.Write([]byte(recvStr)) // 发送数据
	}
}

func main() {
    
    
	fmt.Println("----------服务器已经开启----------")
	listen, err := net.Listen("tcp", "127.0.0.1:20000")
	if err != nil {
    
    
		fmt.Println("listen failed, err:", err)
		return
	}
	for {
    
    
		conn, err := listen.Accept() // 建立连接
		if err != nil {
    
    
			fmt.Println("accept failed, err:", err)
			continue
		}
		go process(conn) // 启动一个goroutine处理连接
	}
}

TCP programming client

  • The workflow of the client in Go language:
  • (1) Establish a connection with the server
  • (2) Send message
  • (3) Disconnect

Client code

package main
import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
)

//客户端
func main() {
    
    
	conn,err :=net.Dial("tcp","127.0.0.1:20000")
	if err!=nil{
    
    
		fmt.Println("err:",err)
		return
	}
	defer conn.Close()//关闭连接
	inputReader :=bufio.NewReader(os.Stdin)
	for{
    
    
		input,_:=inputReader.ReadString('\n')//读取用户输入
		inputInfo :=strings.Trim(input,"\r\n")
		if strings.ToUpper(inputInfo) == "Q"{
    
    
			//如果输入了Q就退出
			return
		}
		_,err =conn.Write([]byte(inputInfo))//发送数据
		if err!=nil{
    
    
			return
		}
		buf :=[512]byte{
    
    }
		n,err :=conn.Read(buf[:])
		if err!=nil{
    
    
			fmt.Println("recv failed,err",err)
			return
		}
		fmt.Println("发送成功一条消息:",string(buf[:n]))
	}
}


defer: In the Go language, the defer statement will be called at the end of the function, and the defer statement will still be executed even if an exception occurs during the execution of the following statement.
It should be noted that if a parameter is referenced in the defer statement, the value of the parameter will be the value when the program reaches the defer line, and has nothing to do with the following statement

Guess you like

Origin blog.csdn.net/H1517043456/article/details/112785245