This article illustrates the simple TCP client and server implementation method of Go language servers development. Share to everyone for your reference. The implementation methods are as follows:
The go language has powerful server development support, demonstrating the most basic server development: Communication between client and server via TCP protocol.
One service side, opening a new goroutine for each client
Copy Code code as follows:
Func serverbase () {
Fmt. Println ("Starting the server ...")
Create Listener
Listener, err: = Net. Listen ("TCP", "192.168.1.27:50000")
If Err!= nil {
Fmt. Println ("Error Listening:", err. Error ())
Return
}
Listen and accept connections from clients:
for {
Conn, err: = Listener. Accept ()
If Err!= nil {
Fmt. Println ("Error accepting:", err. Error ())
Return
}
Create a goroutine for each request.
Go Doserverstuff (conn)
}
}
Func Doserverstuff (Conn net. Conn) {
Fmt. PRINTLN ("New Connection:", Conn.) LOCALADDR ())
for {
BUF: = Make ([]byte, 1024)
Length, err: = conn. Read (BUF)
If Err!= nil {
Fmt. Println ("Error reading:", err. Error ())
Return
}
Fmt. Println ("Receive Data from Client:", String (Buf[:length]))
}
}
Two clients connect to the server and send data
Copy Code code as follows:
Func ClientBase () {
Open Connection:
Conn, Err: = Net. Dial ("TCP", "192.168.1.27:50000")
If Err!= nil {
Fmt. PRINTLN ("Error dial:", err. Error ())
Return
}
Inputreader: = Bufio. Newreader (OS. Stdin)
Fmt. PRINTLN ("Please input your name:")
ClientName, _: = inputreader.readstring (' \ n ')
Inputclientname: = Strings. Trim (ClientName, "\ n")
Send info to server until Quit
for {
Fmt. Println ("What do you send to the server?") Type Q to quit. ")
Content, _: = inputreader.readstring (' \ n ')
Inputcontent: = Strings. Trim (content, "\ n")
if inputcontent = = "Q" {
Return
}
_, ERR: = conn. Write ([]byte (inputclientname + "says" + inputcontent))
If Err!= nil {
Fmt. Println ("Error Write:", err.) Error ())
Return
}
}
}
Note: Because Liteide does not support running multiple programs at the same time, it is necessary to run both the server side and (one or more) clients at the terminal through the Go Run command to observe the support of the servers for concurrent access.
I hope this article will help you with your go language program.