How to read and write data from/to network connections using bufio in Go?

To read and write data from/to network connections using bufio in Go, you can follow these steps:

  1. Import bufio package:
import "bufio"
  1. Create a new bufio.Reader by passing a net.Conn or io.Reader to its NewReader() function. For writing, you can create a new bufio.Writer by passing a net.Conn or io.Writer to its NewWriter() function.
reader := bufio.NewReader(conn) // conn represents the network connection writer := bufio.NewWriter(conn)
  1. To read data from the network connection, you can use ReadString(delim byte) or ReadBytes(delim byte) functions of the bufio.Reader. These functions read until the delimiter byte or an error occurs, and return the read bytes as a string or a byte slice, respectively.
data, err := reader.ReadString('\n') // Read until newline character // Handle error and use data
  1. To write data to the network connection, you can use the Write(data []byte) or WriteString(s string) functions of the bufio.Writer. These functions write the given data to the network connection.
_, err := writer.WriteString("Hello, World!\n") // Handle error err = writer.Flush() // Flush the buffered data to the network connection // Handle error

Note: The Flush() function is used to ensure that all the buffered data has been written to the network connection. It is important to call this function after writing data using bufio.Writer to make sure that data is sent immediately.

Here is an example that demonstrates reading and writing data from/to a TCP connection using bufio:

package main import ( "bufio" "fmt" "net" "os" ) func main() { // Connect to a TCP server conn, err := net.Dial("tcp", "localhost:8080") if err != nil { fmt.Println("Error connecting:", err) os.Exit(1) } defer conn.Close() reader := bufio.NewReader(conn) writer := bufio.NewWriter(conn) // Read data from the network connection data, err := reader.ReadString('\n') if err != nil { fmt.Println("Error reading:", err) os.Exit(1) } fmt.Println("Received:", data) // Write data to the network connection _, err = writer.WriteString("Hello, Server!\n") if err != nil { fmt.Println("Error writing:", err) os.Exit(1) } err = writer.Flush() if err != nil { fmt.Println("Error flushing:", err) os.Exit(1) } fmt.Println("Sent: Hello, Server!") }

In this example, we first connect to a TCP server and create bufio.Reader and bufio.Writer. Then, we use bufio.Reader to read data from the connection and bufio.Writer to write data to the connection. Finally, we flush the buffered data and print the sent and received messages.