This is a creation in Article, where the information may have evolved or changed.
Overview
Golang as a very beautiful development language in recent years, in fact, with a wide range of graphics interface, Web framework, image engine and so on.
Because of its language features simplifies concurrent/multi-core development, it has received a lot of attention. The use of it for server development is also very high school and concise.
Not much nonsense. The purpose of this project is to develop a simple TCP protocol-based server/client using Golang.
Pre-knowledge
First, we need to look at the following packages and features under Golang:
Goroutine
Goroutine is a lightweight thread that, as a language feature of the Golang language, can be easily developed in Golang in a multithreaded way. With the Go keyword, we can put any method/function in a new goroutine to execute.
Lab 01:
In the * * Home folder * * In the LAB environment * *, create a text document named Test.go and start writing the following code
package main import ( "fmt" ) var quit chan bool = make(chan bool) func main() { go testGorountine() <-quit } func testGorountine() { for i := 0; i < 10; i++ { fmt.Println("Hello world!") } quit <- true }
Then, open the Xfce terminal and type the command
Go Run test.go
We will see the output of the terminal and we can see 10 lines "Hello World". Here, our Hello World program uses Gorountine to create a multithreaded/coprocessor, and then ends the main thread by using the channel to wait for the open coprocessor to finish.
NET Package
In the net package, we provide APIs for common network I/O operations, including Listen, Accept, Write, read, and so on in our experiments. Specific reference Links: http://godoc.golangtc.com/pkg/net/
Bufio Bag
The BUFIO package provides a set of cached I/O read and write operations, which are used when our servers communicate with clients on the data. Reference Link: http://godoc.golangtc.com/pkg/bufio/
You will then need to have a basic understanding of the TCP server * * with long connections:
Client initiates a connection to the server, the server accepts the client connection, and both sides establish the connection. After the client and server have completed a read and write, the connection between them is not actively closed, and subsequent read and write operations continue to use the connection. On this concept, there are a lot of references on the Internet, if not clear, just Google a bit ~