-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathtest_unix_socket_server.go
More file actions
107 lines (89 loc) · 2.27 KB
/
Copy pathtest_unix_socket_server.go
File metadata and controls
107 lines (89 loc) · 2.27 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package api
import (
"fmt"
"net"
"os"
"sync"
)
type Server struct {
Listener net.Listener
StopChan chan struct{}
Wg sync.WaitGroup
}
func CreateTempFile(dir, prefix, suffix string) (string, error) {
// Get the default temporary directory for the OS
if dir == "" {
dir = os.TempDir()
}
// Create a temporary file with the specified prefix and suffix
tempFile, err := os.CreateTemp(dir, prefix+"*"+suffix)
if err != nil {
return "", fmt.Errorf("failed to create temp file: %w", err)
}
// Close the file to release the file descriptor
tempFile.Close()
// Return the name of the created file
return tempFile.Name(), nil
}
func createUnixSocket(socketPath string) (net.Listener, error) {
// Clean up the socket file if it already exists
_ = os.Remove(socketPath)
// Create a Unix domain socket
listener, err := net.Listen("unix", socketPath)
if err != nil {
return nil, fmt.Errorf("failed to create Unix domain socket: %w", err)
}
return listener, nil
}
// StartServer starts the server in a goroutine and returns a stop function
func StartUnixSocketServer(socketPath string) (*Server, error) {
listener, err := createUnixSocket(socketPath)
if err != nil {
return nil, err
}
server := &Server{
Listener: listener,
StopChan: make(chan struct{}),
}
server.Wg.Go(func() {
for {
conn, err := server.Listener.Accept()
if err != nil {
select {
case <-server.StopChan:
return
default:
fmt.Println("Error accepting connection:", err)
continue
}
}
// Handle each connection in a separate goroutine
server.Wg.Add(1)
go func(conn net.Conn) {
defer server.Wg.Done()
defer conn.Close()
// Handle incoming data from the connection
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("Error reading from connection:", err)
return
}
fmt.Printf("Received: %s\n", string(buf[:n]))
// Example: Write a response back
_, err = conn.Write([]byte("Hello from server\n"))
if err != nil {
fmt.Println("Error writing to connection:", err)
return
}
}(conn)
}
})
return server, nil
}
// StopServer stops the server and waits for all goroutines to finish
func (s *Server) Stop() {
close(s.StopChan)
s.Listener.Close()
s.Wg.Wait()
}