Network programming used in GO language (TCP programming)

1, Basic introduction

One of the main design goals of Golang is to face large-scale back-end service programs. Network communication is an essential and crucial part of the server-side programs.
1. There are two types of network programming:

  1. TCP socket programming is the mainstream of network programming. TCP socket programming is called because the underlying layer is based on Tcp/ip protocol For example: QQ chat
  2. For the http programming of b/s structure, when we use the browser to access the server, we use the http protocol, and the bottom layer of http is still implemented with tcp socket. For example: Jingdong Mall [this belongs to go web development]
    2. TCP / IP protocol
    CP/IP (Transmission Control Protocol/Internet Protocol) is short for transmission control protocol / Internet protocol, which is also called network communication protocol in Chinese. This protocol is the most basic protocol of the Internet and the basis of the Internet. In short, it is composed of the IP protocol of the network layer and the TCP protocol of the transmission layer.

    3. OSI and TCP / IP reference model (3 volumes of TCP / IP protocol are recommended)

    4. ip address
    **Overview: * * every host and router on the internet has an ip address, which includes network number and host number. The ip address includes ipv4(32-bit) or ipv6(128 bit) You can view it through ipconfig

    5. Port - Introduction
    The port we refer to here does not refer to the physical port, but specifically refers to the port in the TCP/IP protocol
    Logical port.

If the IP address is compared to a house, the port is the door to and from the house. There are only a few real houses
Door, but the port of an IP address can be 65536 (i.e. 256) × 256) more! The port is the through end
The port number is only an integer, ranging from 0 to 65535 (256) × 256-1)

6. Port - Classification

  • 0 is reserved port

  • 1-1024 are fixed ports (not used by programmers)

    Also known as famous port, it is fixed by some programs and not used by general programmers
    22: SSH Remote Login Protocol 23: telnet usage 21: ftp usage
    25: smtp service usage 80: iis usage 7: echo service

  • 1025-65535 is a dynamic port

    These ports are available to programmers

7. Port - use caution

  1. In the computer (especially as a server), open fewer ports as much as possible
  2. A port can only be monitored by one program
  3. If you use netstat – an, you can check which ports of the machine are listening
  4. You can use netstat – anb to check the pid of the listening port and close the unsafe port in combination with the task manager

2, Client and server of tcp socket programming

The following figure shows the network distribution of clients and servers in Golang socket programming

3, TCP quick start case

1. Server
Processing flow of the server:

  • Listening port 8888

  • Receive the tcp link of the client and establish the link between the client and the server

  • Create goroutine to process the request of the link (usually the client will send the request package through the link)

    2. Client

Processing flow of client:

  • Establish a link with the server
  • Send the request data [terminal] and receive the result data returned by the server
  • Close link

3. Simple program diagram

4. Server side functions:

  1. Write a server-side program to listen on port 8888
  2. You can create links with multiple clients
  3. After the link is successful, the client can send data, and the server can accept the data and display it on the terminal
  4. First use telnet to test, and then write the client program to test

Server code:

package main

import (
    "net"//When developing network socket, net contains network related methods and functions

func Server()  {
        // The server created by the Listen function
        //tcp: network protocol
        // /: 8888 local IP and port
        l, err := net.Listen("tcp", "")
        if err != nil {
        defer l.Close()//Delay close listen
        Cycle waiting for client access
        for {

            conn, err := l.Accept()
            if err != nil {
            fmt.Printf("Access client information: con=%v client ip=%v
", conn, conn.RemoteAddr().String())

            go handleConnection(conn)

            // go func(c net.Conn) {

            //  io.Copy(c, c)

            //  c.Close()
            // }(conn)

//The server processes the data received from the client
func handleConnection(c net.Conn){  
    defer c.Close()//Close conn

    for {

        //1. Wait for the client to send information through conn
        //2. If the client does not wrtie [send], the process will be blocked here
        fmt.Printf("The server is waiting for the client%s Send message
", c.RemoteAddr().String())
        buf := make([]byte, 1024 )
        n, err := c.Read(buf)
        if err != nil {

        //3. Display the content sent by the client to the terminal of the server

func main()  {

5. Client functions:
1. Write a client-side program that can link to the 8888 port on the server-side
2. the client can send single line data and then exit
3. It can input data through the terminal (input one line and send one line) and send it to the server []
4. Enter exit at the terminal to exit the program

Client code:

package main

import (

func Client()  {

    conn, err := net.Dial("tcp", "")
    if err != nil {

    //The client can send a single line of data and then exit
    reader := bufio.NewReader(os.Stdin) //os.Stdin stands for standard input [terminal]
    for {
        //Read a line of user input from the terminal and prepare to send it to the server
        line, err := reader.ReadString('
        if err != nil {
        line = strings.Trim(line,"

        if line == "exit" {
            fmt.Println("User exits client")
        //Then send the line to the server
        conent, err := conn.Write([]byte(line + "
        if err != nil {
        fmt.Printf("Client sent %d Bytes of data to the server
", conent)

func main()  {

Tags: Java Back-end

Posted by pheagey on Mon, 18 Apr 2022 12:01:07 +0930