Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
}
}
@blizard863
Copy link

blizard863 commented Apr 21, 2017

learn

@sundarv85
Copy link

sundarv85 commented May 13, 2017

When I exit without the ln.Close() being called, then restart results in Listen error: listen unix .sock: bind: address already in use exit status 1. Anyway to handle this?

@tierpod
Copy link

tierpod commented May 25, 2017

When you call ln.Close() this function remove socket file /tmp/go.sock. You can stop your program, remove this file manually and start program.

@NaihongGuo
Copy link

NaihongGuo commented Nov 21, 2017

// 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")

@utkarshmani1997
Copy link

utkarshmani1997 commented May 24, 2018

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

Jiang1155 commented May 24, 2021

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