Build TCP server and client
Introduction to TCP Basics
TCP protocol is a safe, reliable, stable and orderly datagram transmission protocol. If the network layer (through ip address) solves the problem of host identification, TCP protocol (through port number) solves the problem of how to identify the only process on the host.
TCP also defines the request sequence number and confirmation sequence number of datagrams to ensure the accuracy and order of messages.
TCP ensures the security of transmission through three handshakes and four waves.
Server Listen function
Listen function:
func Listen(network, address string) (Listener, error)
-
Network: network type. tcp or udp can be filled in.
-
Address: set the server address. The format is [ip]: port. ip can be omitted. The default value is 0.0 zero
-
Error: return nil to indicate no error, otherwise there is an error
-
Listener: listener object, used for subsequent step processing
- Listener:
// A Listener is a generic network listener for stream-oriented protocols. // // Multiple goroutines may invoke methods on a Listener simultaneously. type Listener interface { // Accept waits for and returns the next connection to the listener. Accept() (Conn, error) // Close closes the listener. // Any blocked Accept operations will be unblocked and return errors. Close() error // Addr returns the listener's network address. Addr() Addr }
- Conn returned by Listener#Accept:
// Conn is a generic stream-oriented network connection. // // Multiple goroutines may invoke methods on a Conn simultaneously. type Conn interface { // Read reads data from the connection. // Read can be made to time out and return an error after a fixed // time limit; see SetDeadline and SetReadDeadline. Read(b []byte) (n int, err error) // Write writes data to the connection. // Write can be made to time out and return an error after a fixed // time limit; see SetDeadline and SetWriteDeadline. Write(b []byte) (n int, err error) // Close closes the connection. // Any blocked Read or Write operations will be unblocked and return errors. Close() error // LocalAddr returns the local network address. LocalAddr() Addr // RemoteAddr returns the remote network address. RemoteAddr() Addr // SetDeadline sets the read and write deadlines associated // with the connection. It is equivalent to calling both // SetReadDeadline and SetWriteDeadline. // // A deadline is an absolute time after which I/O operations // fail instead of blocking. The deadline applies to all future // and pending I/O, not just the immediately following call to // Read or Write. After a deadline has been exceeded, the // connection can be refreshed by setting a deadline in the future. // // If the deadline is exceeded a call to Read or Write or to other // I/O methods will return an error that wraps os.ErrDeadlineExceeded. // This can be tested using errors.Is(err, os.ErrDeadlineExceeded). // The error's Timeout method will return true, but note that there // are other possible errors for which the Timeout method will // return true even if the deadline has not been exceeded. // // An idle timeout can be implemented by repeatedly extending // the deadline after successful Read or Write calls. // // A zero value for t means I/O operations will not time out. SetDeadline(t time.Time) error // SetReadDeadline sets the deadline for future Read calls // and any currently-blocked Read call. // A zero value for t means Read will not time out. SetReadDeadline(t time.Time) error // SetWriteDeadline sets the deadline for future Write calls // and any currently-blocked Write call. // Even if write times out, it may return n > 0, indicating that // some of the data was successfully written. // A zero value for t means Write will not time out. SetWriteDeadline(t time.Time) error }
Client Dial function
Dial function:
func Dial(network, address string) (Conn, error)
-
Network: network type. tcp or udp can be filled in.
-
Address: set the server address. The format is [ip]: port. ip can be omitted. The default value is 0.0 zero
-
Error: return nil to indicate no error, otherwise there is an error
-
Conn: the connection object that communicates with the server.
Note: the specific information of Conn object has been given above and will not be repeated here.
Examples of setting up TCP server and client
- TCP server
import ( "fmt" "log" "net" ) func main() { // 1. Bind ip and port and set listening listener, err := net.Listen("tcp", "localhost:8888") if err != nil { log.Panic("Failed to Listen", err) } // Delay shutdown and release resources defer listener.Close() // 2. Cycle and wait for a new connection for { // Get new connection from connection list conn, err := listener.Accept() if err != nil { fmt.Println("Failed to Accept", err) } // 3. Communicate with the new connection (in order to prevent asynchronous blocking, the asynchronous coroutine is opened here for function call) go handle_conn(conn) } } /** * Process connection */ func handle_conn(conn net.Conn) { defer conn.Close() fmt.Println("New connection ", conn.RemoteAddr()) // signal communication buf := make([]byte, 256) for { // Read from the network readBytesCount, err := conn.Read(buf) if err != nil { fmt.Println("Failed to read", err) break } // Tip: the effect of buf[:n] is to read bytes from buf [total length - n] to buf[n] fmt.Println("Data received by the server:\t", string(buf[:readBytesCount])) // Write back to the network -- write back what you receive, that is, echo back to the server writeByteCount, err := conn.Write(buf[:readBytesCount]) if err != nil { fmt.Println("Failed to write", err) break } fmt.Printf("write success %d bytes\n", writeByteCount) } }
- TCP Client
import ( "fmt" "net" "os" ) func main() { // 1. Establish connection conn, err := net.Dial("tcp", "localhost:8888") if err != nil { fmt.Println("Failed to Dial") return } // Delay shutdown and release resources defer conn.Close() // 2. Communication with server buf := make([]byte, 256) for { // 2.1 reading input from console readBytesCount, _ := os.Stdin.Read(buf) // 2.2 write to network (i.e. send request) conn.Write(buf[:readBytesCount]) // 2.3 read network (i.e. get response) readBytesCount, _ = conn.Read(buf) // 2.4 output to console // Tip: the effect of buf[:n] is to read bytes from buf [total length - n] to buf[n] os.Stdout.Write(buf[:readBytesCount]) } }
- Communication test
Start the server side first, then the client side, and then make any input on the console of the client side to trigger the TCP request,
- On the server console, you can see the request information from the client
- On the client console, you can see the response information from the server
^_^ Compiled by Gao ye from Go language blockchain application development from introduction to mastery
^_^ This article has been included in Programmer growth notes By JustryDeng