/*server.go * *
Package Main
Import (
"Bufio"
"FMT"
"NET"
"Time"
)
Func Main () {
var unixaddr *net. Unixaddr
UNIXADDR, _ = net. Resolveunixaddr ("Unix", "/tmp/unix_sock")
Unixlistener, _: = Net. Listenunix ("Unix", Unixaddr)
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))
Msg: = time. Now (). String () + "\ n"
B: = []byte (msg)
Conn. Write (b)
}
}
/* Client.go */
Package Main
Import (
"Bufio"
"FMT"
"NET"
"Time"
)
var Quitsemaphore chan bool
Func Main () {
var unixaddr *net. Unixaddr
UNIXADDR, _ = net. Resolveunixaddr ("Unix", "/tmp/unix_sock")
Conn, _: = Net. Dialunix ("Unix", Nil, unixaddr)
Defer Conn. Close ()
Fmt. Println ("connected!")
Go onmessagerecived (conn)
B: = []byte ("time\n")
Conn. Write (b)
<-quitsemaphore
}
Func onmessagerecived (Conn *net. Unixconn) {
Reader: = Bufio. Newreader (conn)
for {
MSG, err: = Reader. ReadString (' \ n ')
Fmt. PRINTLN (msg)
If err! = Nil {
Quitsemaphore <-True
Break
}
Time. Sleep (time. Second)
B: = []byte (msg)
Conn. Write (b)
}
}
Go Language implementation UNIX domain socket client/server