Skip to content

Instantly share code, notes, and snippets.

@hakobe
Created September 23, 2016 16:33
Show Gist options
  • Save hakobe/6f70d69b8c5243117787fd488ae7fbf2 to your computer and use it in GitHub Desktop.
Save hakobe/6f70d69b8c5243117787fd488ae7fbf2 to your computer and use it in GitHub Desktop.
golang unix domain socket
package main
import (
"io"
"log"
"net"
"time"
)
func reader(r io.Reader) {
buf := make([]byte, 1024)
for {
n, err := r.Read(buf[:])
if err != nil {
return
}
println("Client got:", string(buf[0:n]))
}
}
func main() {
c, err := net.Dial("unix", "/tmp/go.sock")
if err != nil {
log.Fatal("Dial error", err)
}
defer c.Close()
go reader(c)
for {
msg := "hi"
_, err := c.Write([]byte(msg))
if err != nil {
log.Fatal("Write error:", err)
break
}
println("Client sent:", msg)
time.Sleep(1e9)
}
}
package main
import (
"log"
"net"
"os"
"os/signal"
"syscall"
)
func echoServer(c net.Conn) {
for {
buf := make([]byte, 512)
nr, err := c.Read(buf)
if err != nil {
return
}
data := buf[0:nr]
println("Server got:", string(data))
_, err = c.Write(data)
if err != nil {
log.Fatal("Writing client error: ", err)
}
}
}
func main() {
log.Println("Starting echo server")
ln, err := net.Listen("unix", "/tmp/go.sock")
if err != nil {
log.Fatal("Listen error: ", err)
}
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt, syscall.SIGTERM)
go func(ln net.Listener, c chan os.Signal) {
sig := <-c
log.Printf("Caught signal %s: shutting down.", sig)
ln.Close()
os.Exit(0)
}(ln, sigc)
for {
fd, err := ln.Accept()
if err != nil {
log.Fatal("Accept error: ", err)
}
go echoServer(fd)
}
}
@utkarshmani1997
Copy link

How can we unit test this ? I don't find any reference to get started with unit testing of unix domain sockets.

@Jiang1155
Copy link

// So, servers should unlink the socket pathname prior to binding it.
// https://troydhanson.github.io/network/Unix_domain_sockets.html
syscall.unlink("/tmp/go.sock")
log.Println("Starting echo server")
ln, err := net.Listen("unix", "/tmp/go.sock")

unlink should be Unlink ( capitalize u).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment