本文实例讲述了Go语言服务器开发之简易TCP客户端与服务端实现方法。分享给大家供大家参考。具体实现方法如下:
Go语言具备强大的服务器开发支持,这里示范了最基础的服务器开发:通过TCP协议实现客户端与服务器的通讯。
一 服务端,为每个客户端新开一个goroutine
复制代码 代码如下:
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]))
}
}
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]))
}
}
二 客户端 连接服务器,并发送数据
复制代码 代码如下:
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
}
}
}
//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
}
}
}
注:由于LiteIDE不支持同时运行多个程序,所以需要在终端通过 go run 命令来同时运行服务端和(一个或多个)客户端,可观察到服务器对并发访问的支持。
希望本文所述对大家的Go语言程序设计有所帮助。