-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
45 lines (38 loc) · 971 Bytes
/
server.go
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
// server.go
// Package main implements server-related functions and variables, including the TCP listeners.
package main
import (
"context"
"fmt"
"net"
)
// startListener starts a TCP listener on the specified network and address.
// It accepts incoming connections and spawns a goroutine to handle each client.
func startListener(ctx context.Context, network, address string) error {
ln, err := net.Listen(network, address)
if err != nil {
return err
}
defer ln.Close()
fmt.Printf("Server is listening on %s (%s)...\n", address, network)
for {
select {
case <-ctx.Done():
return nil
default:
}
conn, err := ln.Accept()
if err != nil {
select {
case <-ctx.Done():
return nil
default:
fmt.Printf("Error accepting %s connection: %v\n", network, err)
continue
}
}
// Create a child context for the client
clientCtx, clientCancel := context.WithCancel(ctx)
go handleClient(clientCtx, clientCancel, conn)
}
}