-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
78 lines (65 loc) · 1.99 KB
/
Copy pathserver.go
File metadata and controls
78 lines (65 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package tcp
import (
"bufio"
"fmt"
"io"
"log"
"net"
"time"
)
// RunTCPServer is a core systems programming example demonstrating how edge servers
// like Envoy or NGINX accept raw byte streams, frame them, and handle timeouts.
func RunTCPServer(address string) {
// Listen on TCP IPv4/IPv6 port
listener, err := net.Listen("tcp", address)
if err != nil {
log.Fatalf("Failed to bind TCP port: %v\n", err)
}
defer listener.Close()
log.Printf("TCP Server actively listening on %s...\n", address)
for {
// Accept incoming connection (blocking call)
conn, err := listener.Accept()
if err != nil {
log.Printf("Failed to accept connection: %v\n", err)
continue
}
// Handle each connection concurrently in its own goroutine
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
remoteAddr := conn.RemoteAddr().String()
log.Printf("New TCP connection established from %s\n", remoteAddr)
defer func() {
log.Printf("Closing TCP connection for %s\n", remoteAddr)
_ = conn.Close()
}()
// Apply Keep-Alive and Read deadlines to prevent "Slowloris" attacks!
// Real-world proxies strictly configure connection drop horizons.
deadlineDuration := 30 * time.Second
_ = conn.SetReadDeadline(time.Now().Add(deadlineDuration))
// Buffer reader for handling arbitrary packet framing
reader := bufio.NewReader(conn)
for {
// Read until newline (simplistic framing)
message, err := reader.ReadString('\n')
if err != nil {
// Expected when connection is closed remotely cleanly (EOF).
if err != io.EOF {
log.Printf("Read error for %s: %v\n", remoteAddr, err)
}
break
}
// Refresh the deadline on successful packet read
_ = conn.SetReadDeadline(time.Now().Add(deadlineDuration))
log.Printf("Received stream from %s: %s", remoteAddr, message)
// Acknowledge receipt
ack := []byte(fmt.Sprintf("ACK: %s", message))
_, writeErr := conn.Write(ack)
if writeErr != nil {
log.Printf("Write failed for %s: %v\n", remoteAddr, writeErr)
break
}
}
}