废话不多说,直接上code
unix server
package main
import (
"bufio"
"fmt"
"net"
"time"
)
func main() {
var unixAddr *net.UnixAddr
unixAddr, err := net.ResolveUnixAddr("unix", "/tmp/usk.sock")
if err != nil {
fmt.Println("resolve unix addr fail: " + err)
}
unixListener, err := net.ListenUnix("unix", unixAddr)
if err != nil {
fmt.Println("listen unix addr fail: " + err)
}
defer unixListener.Close()
for {
unixConn, err := unixListener.AcceptUnix()
if err != nil {
continue
}
fmt.Println("A client connected : " + unixConn.RemoteAddr().String())
go unixPipe(unixConn)
}
}
func unixPipe(conn *net.UnixConn) {
ipStr := conn.RemoteAddr().String()
defer func() {
fmt.Println("disconnected :" + ipStr)
conn.Close()
}()
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
return
}
fmt.Println(string(message))
// lua cosoket need '\n'
msg := time.Now().String() + "\n"
b := []byte(msg)
conn.Write(b)
}
}
注意: '\n' lua socket
nginx lua client
location /t/tcp {
resolver 8.8.8.8;
content_by_lua_block {
local sock = ngx.socket.tcp()
local ok, err = sock:connect("www.baidu.com", 80)
if not ok then
ngx.say("failed to connect to baidu: ", err)
return
end
ngx.say("successfully connected to baidu!")
sock:close()
}
}
location /t/unix {
resolver 8.8.8.8;
content_by_lua_block {
local sock = ngx.socket.tcp()
sock:settimeout(300) -- 0.3 second timeout
local ok, err = sock:connect("unix:/tmp/usk.sock")
if not ok then
ngx.say("failed to connect to unix: ", err)
return
end
ngx.say("successfully connected to unix!")
local bytes, err = sock:send("I am nginx\n")
if not bytes then
ngx.say("failed to send query: ", err)
return
end
local chunk,err = sock:receive()
if not chunk then
ngx.say("failed to receive a chunk: ", err)
return
end
ngx.say("content: ", chunk)
sock:close()
}
}
测试命令
➜ /tmp curl 127.0.0.1:8080/t/tcp
successfully connected to baidu!
➜ /tmp curl 127.0.0.1:8080/t/unix
successfully connected to unix!
content: 2020-10-09 03:06:07.196395662 +0000 UTC m=+9.032989967