Reputation:
I am practicing to use Unix socket together with bufio. This is the program:
// Register server socket
os.Remove("serversock")
socket, err := net.ListenUnix("unix", &net.UnixAddr{"serversock", "unix"})
if err != nil {
panic(err)
}
go func() {
for {
// Accept new connection
conn, err := socket.Accept()
if err != nil {
panic(err)
}
fmt.Println("Got connection")
reader := bufio.NewReader(conn)
line, err := reader.ReadString(byte('\n'))
if err != nil {
panic(err)
}
fmt.Println("Got line", line)
}
}()
// Client connection
conn, err := net.DialUnix("unix", nil, &net.UnixAddr{"serversock", "unix"})
writer := bufio.NewWriter(conn)
n, err := writer.WriteString("hello world\n")
if err != nil {
panic(err)
}
fmt.Println("Written", n)
// Client wait
time.Sleep(1 * time.Second)
When it runs, it prints:
Written 13
Got connection
And then exists, so the server does not seem to get the message. What did I do wrong?
Upvotes: 1
Views: 218
Reputation: 49245
Your writer is buffered, it doesn't flush the buffer when you WriteString()
to it. Simply call writer.Flush()
and it will actually send the line. You can also try writing directly to the socket and see what happens.
Also your accept loop should look like this:
go func() {
for {
// Accept new connection
conn, err := socket.Accept()
if err != nil {
panic(err)
}
fmt.Println("Got connection")
reader := bufio.NewReader(conn)
//spawn a goroutine that has a read loop
go func(reader *bufio.Reader) {
for {
line, err := reader.ReadString(byte('\n'))
if err != nil {
panic(err)
}
fmt.Println("Got line", line)
}
}(reader)
}
}()
Upvotes: 1