This article describes the simple TCP client and server implementation method for Go language server development. Share it for your reference. The specific implementation method is as follows:
The Go language has powerful server development support, and here demonstrates the most basic server development: the communication between the client and the server through the TCP protocol.
1. Server, open a new goroutine for each client
("Starting the server...")
//create listener
listener, err := ("tcp", "192.168.1.27:50000")
if err != nil {
("Error listening:", ())
return
}
// listen and accept connections from clients:
for {
conn, err := ()
if err != nil {
("Error accepting:", ())
return
}
//create a goroutine for each request.
go doServerStuff(conn)
}
}
func doServerStuff(conn ) {
("new connection:", ())
for {
buf := make([]byte, 1024)
length, err := (buf)
if err != nil {
("Error reading:", ())
return
}
("Receive data from client:", string(buf[:length]))
}
}
2 Client Connect to the server and send data
//open connection:
conn, err := ("tcp", "192.168.1.27:50000")
if err != nil {
("Error dial:", ())
return
}
inputReader := ()
("Please input your name:")
clientName, _ := ('\n')
inputClientName := (clientName, "\n")
//send info to server until Quit
for {
("What do you send to the server? Type Q to quit.")
content, _ := ('\n')
inputContent := (content, "\n")
if inputContent == "Q" {
return
}
_, err := ([]byte(inputClientName + " says " + inputContent))
if err != nil {
("Error Write:", ())
return
}
}
}
Note: Since LiteIDE does not support running multiple programs at the same time, it is necessary to run the server and (one or more) clients at the terminal through the go run command, and the server's support for concurrent access can be observed.
I hope this article will be helpful to everyone's Go language programming.