go language series -TCP programming

TCP programming

One of the main design goals of Go is to face the large-scale back-end service program. Network communication is the server, and the program is an indispensable and vital part

Basic introduction of network programming

There are two kinds of network programming

Tcp socket programming is the mainstream of network programming. It is called Tcp socket programming because the underlying layer is based on Tcp/ip protocol. For example: QQ chat

When using browser to access server, http protocol is used in http programming of b/s structure, while the underlying http is still implemented by tcp socket. For example: Jingdong Mall [belongs to the go web development category]

To communicate with each other, computers must use network cable, network card or wireless network card

Protocol (tcp/ip)

The abbreviation of TCP/IP(Transmission Control Protocol/Internet Protocol) is translated into Chinese as transmission control protocol / Internet Interconnection Protocol, also known as network communication protocol. This protocol is the most basic protocol of Internet and the foundation of Internet international interconnection network. In short, it is composed of IP protocol of network layer and TCP protocol of transmission layer

OSI and TCP/IP reference model

Recommended book: Volume 3 of tcp/ip protocol

IP address

Every host and router on the internet has an ip address, which includes network number and host number. ip address has ipv4(32-bit) or ipv6(128 bit) which can be viewed by ipconfig

Port - Introduction

The port here refers not to the port in the physical sense, but specifically to the port in the TCP/IP protocol, which is the port in the logical sense

If the IP address is compared to a house, the port is the door to the house. The real house has only a few doors, but the IP address port can have 65536 (that is, 256 × 256) as many! The port is marked by the port number. The port number is only an integer, ranging from 0 to 65535 (256 × 256 - 1)

Port - Classification

0 is reserved

1 - 1024 is a fixed port (not for programmers

It's also called named port, which is fixed by some programs and not used by general programmers

22: SSH Remote Login Protocol 23: telnet use 21: ftp use 25: smtp use 80: iis use 7: echo use

1025 - 65535 are dynamic ports

These ports can be used by programmers

Port - use caution

  1. Open as few ports as possible on the computer (especially on the server)

  2. A port can only be monitored by one program

  3. If you use netstat -an, you can see which ports are listening on this machine

  4. You can use netstat -anb to view the pid of the listening port, and then close the insecure port in combination with task manager

The client and server of tcp socket programming

tcp socket programming, referred to as socket programming, the following figure shows the network distribution of client and server in Go socket programming

A quick introduction to tcp socket programming

Processing flow of server

  1. Listening port 8888

  2. Receive the tcp link of the client and establish the link between the client and the server

  3. Create goroutine to process the link request (usually the client will send the request package through the link)

Process flow of client

  1. Establish a link with the server

  2. Send request data [terminal], receive the result data returned by the server

  3. Close links

Simple program diagram

code implementation

Server side functions:

1. Write a server program and listen on port 8888

2. Can create links with multiple clients

3. After the link is successful, the client can send the data, and the server can accept the data and display it on the terminal

4. First use telnet to test, then write client program to test

import (
   "fmt"
   "net" //When developing network socket, net contains all the methods and functions we need
   _"io"
)

func process(conn net.Conn)  {
   //Here we accept the data sent by the client circularly
   defer conn.Close() //Close conn
   for {
      //Create a new slice
      buf := make([]byte,1024)
      //conn.Read(buf)
      //1. Wait for the client to send information through conn
      //2. If the client does not write [send], the cooperation will be blocked here
      fmt.Printf("Server waiting for client%s Send message\n", conn.RemoteAddr().String())
      n, err := conn.Read(buf) //Read from conn
      if err != nil {
         fmt.Printf("Client exit err = %v", err)
         return // !!!
      }
      //3. Display the content sent by the client to the terminal of the server
      fmt.Print(string(buf[:n]))
   }
}
func main()  {
   fmt.Println("Server starts listening...")
   //net.Listen("tcp", "0.0.0.0:8888")
   //1. tcp indicates that the network protocol used is tcp
   //2. 0.0.0.0:8888 means listening to port 8888 locally
   listen, err := net.Listen("tcp","0.0.0.0:8888")
   if err != nil {
      fmt.Println("listen err = ", err)
      return
   }
   defer listen.Close() // Delay close listen
   //Loop waiting for clients to link me
   for {
      //Waiting for client link
      fmt.Println("Wait for client to link...")
      conn, err := listen.Accept()
      if err != nil {
         fmt.Println("Accept() err =", err)
      } else {
         fmt.Printf("Accept() suc con = %v Client ip = %v\n", conn, conn.RemoteAddr().String())
      }
      //Here we prepare one of its protocols to serve the client
      go process(conn)
   }
   //fmt.Printf("liaten suc = %v\n",listen)
}

Client functions:

1. Write a client program that can link to port 8888 of the server

2. The client can send single line data and then exit

3. Be able to 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

import (
   "bufio"
   "fmt"
   "net"
   "os"
)

func main()  {
   conn, err := net.Dial("tcp", "0.0.0.0:8888")
   if err != nil {
      fmt.Println("client dial err = ", err)
      return
   }
   //Function 1: the client can send single line data and then exit
   reader := bufio.NewReader(os.Stdin) //os.Stdin for standard input [terminal]
   //Read a line of user input from the terminal and prepare to send it to the server
   line, err := reader.ReadString('\n')
   if err != nil {
      fmt.Println("readString err = ", err)
   }
   //Then send line to the server
   n, err := conn.Write([]byte(line))
   if err != nil {
      fmt.Println("conn.Write err =", err)
   }
   fmt.Printf("Client sent %d Byte data and exit", n)
}

Verify that the server program is executed before the client program

Server starts listening
 Waiting for client to link
 Accept() suc con = & {{0xc0007e2c0}} client ip = 127.0.0.1:65393
 Waiting for client to link
 Server is waiting for client 127.0.0.1:65393 to send information

Improve the client

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

func main()  {
   conn, err := net.Dial("tcp", "0.0.0.0:8888")
   if err != nil {
      fmt.Println("client dial err = ", err)
      return
   }
   //Function 1: the client can send single line data and then exit
   reader := bufio.NewReader(os.Stdin) //os.Stdin 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('\n')
      if err != nil {
         fmt.Println("readString err = ", err)
      }
      //Exit if the user enters exit
      line = strings.Trim(line, " \r\n")
      if line == "exit" {
         fmt.Println("Client exit...")
         break
      }

      //Then send line to the server
      _, err = conn.Write([]byte(line + "\n"))
      if err != nil {
         fmt.Println("conn.Write err =", err)
      }
   }
   //fmt.Printf("client sent% d bytes of data and exited", n)
}

Verification

hello zisefeizhu

Server starts listening
 Waiting for client to link
 Accept() suc con = & {{0xc000002c0}} client ip = 127.0.0.1:49248
 Waiting for client to link
 Server is waiting for client 127.0.0.1:49248 to send information
hello zisefeizhu
 Server is waiting for client 127.0.0.1:49248 to send information

Keywords: Go network Programming socket Web Development

Added by kat89 on Wed, 08 Apr 2020 08:05:01 +0300