-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
unix_socket_server.go
65 lines (58 loc) · 1.01 KB
/
unix_socket_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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"encoding/binary"
"log"
"net"
"os"
"syscall"
)
const SockAddr = "/tmp/echo.sock"
func echoServer(c net.Conn) {
header := make([]byte, 4)
buf := make([]byte, 1024*1024*10)
out := make([]byte, 1024*1024*10)
for {
n, err := c.Read(header)
if err != nil {
break
}
length := binary.BigEndian.Uint32(header)
read := 0
for uint32(read) < length {
n, err = c.Read(buf[read:length])
if err != nil {
break
}
read += n
}
binary.BigEndian.PutUint32(out[:4], length)
copy(out[4:], buf[:length])
sent := 0
for uint32(sent) < length+4 {
n, err = c.Write(out[sent : length+4])
if err != nil {
break
}
sent += n
}
}
c.Close()
}
func main() {
if err := os.RemoveAll(SockAddr); err != nil {
log.Fatal(err)
}
syscall.Umask(0)
l, err := net.Listen("unix", SockAddr)
if err != nil {
log.Fatal("listen error:", err)
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Fatal("accept error:", err)
}
go echoServer(conn)
}
}