go20/day09/tcp/server/main.go

72 lines
1.5 KiB
Go
Raw Normal View History

2026-03-29 16:22:28 +08:00
package main
import (
"fmt"
"net"
"io"
)
func main() {
// 1. 监听端口
listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error listening:", err)
return
}
defer listener.Close()
fmt.Println("Server is listening on port 8080")
// 2. 接受连接
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
continue
}
// 3. 处理连接
// 使用 goroutine 并发处理连接
// 这样就可以同时处理多个连接,提高并发能力 (非阻塞)
go handleConnection(conn)
}
}
// 处理连接
// 1. 读取数据
// 2. 处理数据
// 3. 写入数据
func handleConnection(conn net.Conn) {
defer func() {
conn.Close()
fmt.Println("Connection closed by client")
}()
fmt.Println("New connection accepted")
// 4. 循环读取数据
for {
// 4.1 读取数据
buf := make([]byte, 1024)
n, err := conn.Read(buf)
// 如果客户端关闭连接,则退出循环
if err == io.EOF {
fmt.Println("Client closed connection")
break
}
if err != nil {
fmt.Println("Error reading data:", err)
break
}
// 4.3 处理数据
fmt.Println("Read", n, "bytes:", string(buf[:n]))
// 4.2 写入数据
_, err = conn.Write([]byte("Hello, Client! I have received your message: " + string(buf[:n]) + "\n"))
if err != nil {
fmt.Println("Error writing data:", err)
break
}
fmt.Println("Written", n, "bytes:", "Hello, Client! I have received your message: " + string(buf[:n]) + "\n")
}
}