Go 语言 TCP 服务器示例 - 监听端口,处理连接和消息
以下是使用 Go 语言编写的一个简单的 TCP 服务器示例:
package main
import (
"fmt"
"net"
)
func main() {
// 创建 TCP 服务器监听端口
listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error listening:", err.Error())
return
}
defer listener.Close()
fmt.Println("TCP server listening on port 8080")
// 循环等待客户端连接
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting:", err.Error())
return
}
// 处理客户端连接
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
fmt.Println("Client connected:", conn.RemoteAddr())
// 循环处理客户端发送的消息
for {
// 读取客户端发送的数据
data := make([]byte, 1024)
n, err := conn.Read(data)
if err != nil {
fmt.Println("Error reading:", err.Error())
return
}
// 输出客户端发送的数据
fmt.Println("Received message from client:", string(data[:n]))
// 回复客户端消息
_, err = conn.Write([]byte("Message received"))
if err != nil {
fmt.Println("Error writing:", err.Error())
return
}
}
}
这个 TCP 服务器监听 8080 端口,接受客户端连接并处理客户端发送的消息。在 handleConnection 函数中,我们循环读取客户端发送的数据,并输出到控制台上。然后,我们回复客户端一个简单的消息,告知客户端服务器已收到消息。
原文地址: https://www.cveoy.top/t/topic/ngmE 著作权归作者所有。请勿转载和采集!