To read and write data to and from network sockets (TCP/UDP) in Go, you can use the "net" package. Below is an example that demonstrates how to do this using TCP socket.
Reading data from a TCP socket:
package main
import (
"fmt"
"net"
)
func main() {
// Connect to TCP server
conn, err := net.Dial("tcp", "localhost:8080")
if err != nil {
fmt.Println("Error connecting:", err)
return
}
defer conn.Close()
// Read data from the socket
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
fmt.Println("Error reading:", err)
return
}
// Process the received data
data := buffer[:n]
fmt.Println("Received:", string(data))
}
Writing data to a TCP socket:
package main
import (
"fmt"
"net"
)
func main() {
// Start a TCP server
ln, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error starting server:", err)
return
}
defer ln.Close()
// Accept incoming connections
conn, err := ln.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
return
}
defer conn.Close()
// Write data to the socket
data := []byte("Hello, world!")
_, err = conn.Write(data)
if err != nil {
fmt.Println("Error writing:", err)
return
}
}
Note that these examples demonstrate TCP communication, but the process is quite similar for UDP sockets as well. The key difference is using net.DialUDP
and net.ListenUDP
functions to establish the UDP connection.