Go Language implementation UNIX domain socket client/server

Source: Internet
Author: User
Tags unix domain socket

/*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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.