In Go, you can create and use custom I/O streams using sockets or pipes by implementing the io.Reader
and io.Writer
interfaces. Here's how you can do it:
Using Sockets:
import (
"net"
"io"
)
net.Listener
to listen on a specific network address:listener, err := net.Listen("tcp", "localhost:8080")
if err != nil {
// handle error
}
defer listener.Close()
conn, err := listener.Accept()
if err != nil {
// handle error
}
defer conn.Close()
conn
object to read from/write to the socket connection:// Read from the socket connection
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
// handle error
}
data := buffer[:n]
// Write to the socket connection
n, err = conn.Write([]byte("Hello, client!"))
if err != nil {
// handle error
}
Using Pipes:
import (
"io"
"os"
)
io.Pipe()
:reader, writer := io.Pipe()
defer reader.Close()
defer writer.Close()
reader
and writer
objects for reading and writing:// Write to the pipe
go func() {
_, err := writer.Write([]byte("Data from writer"))
if err != nil {
// handle error
}
writer.Close()
}()
// Read from the pipe
buffer := make([]byte, 1024)
n, err := reader.Read(buffer)
if err != nil {
// handle error
}
data := buffer[:n]
These are basic examples to get you started with custom I/O streams using sockets and pipes in Go. You can use these concepts and build more complex functionality as per your requirements.