current position:Home>[golang] walk into go language lesson 24 TCP high-level operation

[golang] walk into go language lesson 24 TCP high-level operation

2021-08-25 18:49:37 I'm Xiaobai

summary

Golang Is a new cross platform programming language . Today, Xiaobai will take you hand in hand into Golang The world of . ( The first 24 course )

 Insert picture description here

Basic knowledge of

Conn Interface

Conn It is a general stream oriented network connection . Multiple Goroutine Can call at the same time Conn The method on the .

net.Listen()

Monitor local network broadcasts .

Format :

net.Listen(network, address string)

Parameters :

  • network: Network mode , “tcp”, “tcp4”, “tcp6”, “unix”, “unixpacket” One out of six
  • address: network address

Example :

listen_socket, err := net.Listen("tcp", "127.0.0.1:8888")

Return value :

  • listen_socket: Listening interface
  • err: error

listener.Accept()

Connect to the client .

Format :

listener.Accept()

Example :

conn, err := listen_socket.Accept()

Return value :

  • conn: Network interface
  • err: error

conn.Read()

Read information .

Format :

conn.Read(b []byte)

Example :

nums, err := conn.Read(buffer)

Return value :

  • nums: Number of bytes read
  • err: error

conn.Write()

Transmit information .

Format :

conn.Write(b []byte)

Example :

conn.Write([]byte("Hi, Server"))

Interactive communication

 Insert picture description here

The server

package main

import (
	"fmt"
	"net"
)

//  Send a message 
func send_info(conn net.Conn) {

	//  Send a message 
	_, err := conn.Write([]byte("Message received"))
	error_check(err)
	fmt.Println(" Send a message : Message received")
}

//  receive messages 
func receive_info(conn net.Conn) {

	//  buffer 
	buffer := make([]byte, 1024)

	//  Cyclic reading 
	for {

		//  Reading data 
		nums, err := conn.Read(buffer)
		if err != nil {
			break
		}

		if nums != 0 {

			//  Get address 
			address := conn.RemoteAddr()
			fmt.Println(" Received a message :", string(buffer[:nums]), " come from :", address)
		}

		//  Send a message 
		send_info(conn)
	}
}

//  Error handling 
func error_check(err error) {
	if err != nil {
		fmt.Println("Error:", err)
	}
}

func main() {

	fmt.Println(" The server is starting ...")

	//  establish TCP Server side 
	listen_socket, err := net.Listen("tcp", "127.0.0.1:8888")
	error_check(err)

	//  close 
	defer listen_socket.Close()

	fmt.Println(" The server is started ,  Waiting for the connection ...")

	//  Start the connection 
	for {

		//  Connect new client 
		conn, err := listen_socket.Accept()
		error_check(err)

		//  Receive every client 
		go receive_info(conn)
	}

}

client

package main

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

//  Send a message 
func send_msg(conn net.Conn) {

	//  Cycle to send 
	for {

		//  Read keyboard input 
		reader := bufio.NewReader(os.Stdin)

		//  Read a line 
		data, _, _ := reader.ReadLine()


		//  received exit,  Close client 
		if string(data) == "exit" {
			fmt.Println(" Client shutdown ")
			break
		}

		//  Send the input string 
		_, err := conn.Write(data)
		if err != nil {
			conn.Close()
			fmt.Println("Error:", err, " Client shutdown ")
			break
		}
	}
}

func main() {

	fmt.Println(" The customer service side is establishing a connection ...")

	//  Set up a network connection 
	conn, err := net.Dial("tcp", "127.0.0.1:8888")
	if err != nil {
		fmt.Println(" Network connection error ")
		os.Exit(1)
	}
	fmt.Println(" The client successfully connected to the server ,  Server address :", conn.RemoteAddr())

	//  Send a message 
	go send_msg(conn)

	//  receive messages 
	buffer := make([]byte, 1024)

	//  Cyclic reception 
	for {
		//  Read message 
		nums, err := conn.Read(buffer)
		if err != nil {
			fmt.Println("Error:", err)
		}
		fmt.Println(" Received a message :", string(buffer[:nums]))
	}

}

Output results :

Server side :

 The server is starting ...
 The server is started ,  Waiting for the connection ...
 Received a message :  hole 1 hole 1,  I'm a hole 2  come from : 127.0.0.1:62831
 Send a message : Message received
 Received a message :  hole 1 hole 1,  I'm a hole 3  come from : 127.0.0.1:55002
 Send a message : Message received

client :

 The customer service side is establishing a connection ...
 The client successfully connected to the server ,  Server address : 127.0.0.1:8888
 hole 1 hole 1,  I'm a hole 3
 Received a message : Message received

copyright notice
author[I'm Xiaobai],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210825184934304Y.html

Random recommended