package main
import (
"fmt"
"net"
)
func main() {
// 监听TCP端口
listener, err := net.Listen("tcp", "localhost:50000")
if err != nil {
fmt.Println("Error listening:", err.Error())
return
}
defer listener.Close()
fmt.Println("Listening on localhost:50000...")
// 无限循环等待并处理连接
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting:", err.Error())
continue
}
go handleConnection(conn)
}
}
// 处理单个连接的函数
func handleConnection(conn net.Conn) {
defer conn.Close()
// 读取客户端发送的数据
buffer := make([]byte, 512)
n, err := conn.Read(buffer)
if err != nil {
fmt.Println("Error reading:", err.Error())
return
}
fmt.Println("Received data:", string(buffer[:n]))
// 回复客户端
_, err = conn.Write([]byte("Hello, client!\n"))
if err != nil {
fmt.Println("Error writing:", err.Error())
return
}
}
go实现TCP服务器
最新推荐文章于 2024-09-16 12:49:58 发布