To read and write data from and to network connections in Go, you can use the net
package which provides a set of functions and types for network operations.
To read data from a network connection, you can use the Read()
method on the net.Conn
type. Here's an example:
package main
import (
"fmt"
"net"
)
func main() {
// Connect to a network address
conn, err := net.Dial("tcp", "example.com:80")
if err != nil {
fmt.Println("Error connecting:", err)
return
}
defer conn.Close()
// Read data from the network connection
buffer := make([]byte, 1024)
bytesRead, err := conn.Read(buffer)
if err != nil {
fmt.Println("Error reading:", err)
return
}
// Process the read data
fmt.Println("Read", bytesRead, "bytes:", string(buffer[:bytesRead]))
}
In this example, we connect to a TCP network address using net.Dial()
and then read data from the connection using conn.Read()
. The read data is stored in a buffer and then processed as needed.
To write data to a network connection, you can use the Write()
method on the net.Conn
type. Here's an example:
package main
import (
"fmt"
"net"
)
func main() {
// Connect to a network address
conn, err := net.Dial("tcp", "example.com:80")
if err != nil {
fmt.Println("Error connecting:", err)
return
}
defer conn.Close()
// Write data to the network connection
message := []byte("Hello, server!")
bytesWritten, err := conn.Write(message)
if err != nil {
fmt.Println("Error writing:", err)
return
}
fmt.Println("Written", bytesWritten, "bytes")
}
In this example, we connect to a TCP network address and then write a message to the connection using conn.Write()
. The number of bytes written is stored in bytesWritten
.