Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Net package – based small application

The complete code has been uploaded to Github github-TCP

Welcome star and Issue

Start by creating two directories, one isclientThe client, the other one isserverThe service side.

1. The connection

1.1 the service side

  • Listening to the connection

Net provides the Listen method, so that the server port listening

ADDRESS := "127.0.0.1:5000"
listener,err := net.Listen("tcp",ADDRESS)
iferr ! =nil {
	fmt.Printf("start tcp server %s failed ,err : %s ",listener,err)
	return
}
defer listener.Close()
Copy the code

1.2 the client

  • Establish a connection

Net provides Dail methods that let clients connect to servers

ADDRESS := "127.0.0.1:5000"
conn,err := net.Dial("tcp",ADDRESS) // Initiate a connection with the server
iferr ! =nil {
	fmt.Printf("dial %s failed; err :%s",ADDRESS,err)
	return
}
Copy the code

2. Communication

2.1 the service side

  • Receiving information

The transmitted data can be Read by.read.

	var data [1024]byte
	var msg string
	reader := bufio.NewReader(os.Stdin)
	for {   // The server is always waiting for incoming data, so use the for loop
		// Receive information
		n,err := conn.Read(data[:])
		if err == io.EOF{
			break
		}
		iferr ! =nil {
			fmt.Printf("read from conn failed,err:%s",err)
			return
		}
		fmt.Println("Access Info : ".string(data[:n]))
	}
	defer conn.Close()
Copy the code

2.2 the client

  • Send a message

It is also possible to transfer data over a transport connection via.write.

	for{ // Let the client keep sending messages, so we need a for loop to keep the connection going
		fmt.Print("Please enter:")
		msg,_ = reader.ReadString('\n')
		msg = strings.TrimSpace(msg)
		if msg == "exit" {
			break
		}
		_, _ = conn.Write([]byte(msg))
	}
Copy the code

3. Reply

When the server receives the message, it should return the message to the client. Indicates that data has been received.

3.1 the service side

The server replies the message

	// Reply to the message
	fmt.Print("Reply message :")
	msg,_ = reader.ReadString('\n')
	msg = strings.TrimSpace(msg)
	if msg == "exit" {
		break
	}
	_ ,_ = conn.Write([]byte(msg))
Copy the code

3.2 the client

The client received the message. Procedure

	// Receive information
	n,err:=conn.Read(data[:])
	if err == io.EOF {
		break
	}
	iferr ! =nil {
		fmt.Println("read from conn failed, err :",err)
		return
	}
	fmt.Println("Reply received :".string(data[:n]))
Copy the code

The last

Xiao Sheng Fan Yi, looking forward to your attention.