-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
65 lines (55 loc) · 1.37 KB
/
Copy pathmain.go
File metadata and controls
65 lines (55 loc) · 1.37 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
// TCP server that listens on localhost:8080
// and echoes back any message it receives.
//
// Usage example:
//
// so run apps/echo-server
package main
import (
"solod.dev/so/conc"
"solod.dev/so/mem"
"solod.dev/so/net"
)
func main() {
// Resolve the local address to listen on.
laddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080")
if err != nil {
panic(err)
}
// Start listening on the local address.
ln, err := net.ListenTCP("tcp", &laddr)
if err != nil {
panic(err)
}
defer ln.Close()
// Serve connections on a fixed set of worker threads.
pool := conc.NewPool(mem.System, conc.PoolOptions{NumThreads: 4})
defer pool.Free()
println("listening on", "127.0.0.1:8080")
// Accept connections and hand them to the pool.
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
// Move the connection to the heap so it outlives this iteration.
connPtr := mem.Alloc[net.TCPConn](mem.System)
*connPtr = conn
// Blocks while every worker is busy and the queue is full,
// which throttles accepting until a worker frees up.
pool.Go(serve, connPtr)
}
}
// serve reads one message from the connection, echoes it back,
// and closes the connection.
func serve(arg any) {
conn := arg.(*net.TCPConn)
defer mem.Free(mem.System, conn)
defer conn.Close()
var buf [256]byte
n, err := conn.Read(buf[:])
if err != nil {
return
}
conn.Write(buf[:n])
}