angle_dtu/angle.go.bak
2025-05-14 17:31:15 +08:00

67 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"fmt"
"io"
"log"
"net"
"time"
)
func handleConnection(conn net.Conn) {
defer conn.Close()
// 客户端地址信息
remoteAddr := conn.RemoteAddr().String()
fmt.Printf("客户端 %s 已连接\n", remoteAddr)
// 设置连接超时
conn.SetReadDeadline(time.Now().Add(time.Hour * 24)) // 24小时超时可以根据需要调整
buffer := make([]byte, 1024)
for {
// 读取客户端发送的数据
n, err := conn.Read(buffer)
if err != nil {
if err == io.EOF {
fmt.Printf("客户端 %s 已断开连接\n", remoteAddr)
} else {
fmt.Printf("从客户端 %s 读取数据时出错: %v\n", remoteAddr, err)
}
break
}
// 在终端显示接收到的数据
receivedData := buffer[:n]
fmt.Printf("从 %s 接收到数据: %s\n", remoteAddr, string(receivedData))
// 可选:回复客户端确认消息
// conn.Write([]byte("服务器已收到消息"))
}
}
func main() {
// 监听端口
port := ":10002"
listener, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("无法监听端口 %s: %v", port, err)
}
defer listener.Close()
fmt.Printf("TCP服务器已启动正在监听端口 %s\n", port)
// 接受连接并处理
for {
conn, err := listener.Accept()
if err != nil {
fmt.Printf("接受连接失败: %v\n", err)
continue
}
// 为每个连接创建一个goroutine
go handleConnection(conn)
}
}