The net package in Go is a fundamental part of the standard library that provides low-level networking primitives. It includes functionalities for TCP, UDP, IP, Unix domain sockets, and more. Whether you're building a simple client-server application or a complex network service, understanding how to use the net package is crucial.
The net package offers several key features:
In this tutorial, we'll explore some practical examples to help you understand how to use these features effectively.
Let's start by creating a simple TCP client and server using the net package.
package main
import (
"bufio"
"fmt"
"net"
)
func handleConnection(conn net.Conn) {
defer conn.Close()
fmt.Println("Connected to:", conn.RemoteAddr())
for {
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
fmt.Println("Error reading:", err.Error())
return
}
fmt.Print("Received message: ", string(message))
}
}
func main() {
listener, err := net.Listen("tcp", "localhost:8080")
if err != nil {
fmt.Println("Error listening:", err.Error())
return
}
defer listener.Close()
fmt.Println("Listening on localhost:8080")
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err.Error())
continue
}
go handleConnection(conn)
}
}
#### Client Example
```go
package main
import (
"bufio"
"fmt"
"net"
"os"
)
func main() {
conn, err := net.Dial("tcp", "localhost:8080")
if err != nil {
fmt.Println("Error connecting:", err.Error())
return
}
defer conn.Close()
for {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter message: ")
text, _ := reader.ReadString('\n')
conn.Write([]byte(text))
}
}
### 2. UDP Client and Server
Now, let's create a simple UDP client and server.
#### Server Example
```go
package main
import (
"fmt"
"net"
)
func handleConnection(conn *net.UDPConn) {
buffer := make([]byte, 1024)
for {
n, addr, err := conn.ReadFromUDP(buffer)
if err != nil {
fmt.Println("Error reading:", err.Error())
return
}
fmt.Printf("Received message: %s from %v\n", string(buffer[:n]), addr)
conn.WriteToUDP([]byte("Message received!"), addr)
}
}
func main() {
addr, err := net.ResolveUDPAddr("udp", "localhost:8081")
if err != nil {
fmt.Println("Error resolving address:", err.Error())
return
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
fmt.Println("Error listening:", err.Error())
return
}
defer conn.Close()
fmt.Println("Listening on localhost:8081")
handleConnection(conn)
}
#### Client Example
```go
package main
import (
"fmt"
"net"
)
func main() {
addr, err := net.ResolveUDPAddr("udp", "localhost:8081")
if err != nil {
fmt.Println("Error resolving address:", err.Error())
return
}
conn, err := net.DialUDP("udp", nil, addr)
if err != nil {
fmt.Println("Error connecting:", err.Error())
return
}
defer conn.Close()
message := []byte("Hello UDP!")
_, err = conn.Write(message)
if err != nil {
fmt.Println("Error writing:", err.Error())
return
}
buffer := make([]byte, 1024)
n, _, err := conn.ReadFromUDP(buffer)
if err != nil {
fmt.Println("Error reading response:", err.Error())
return
}
fmt.Printf("Received response: %s\n", string(buffer[:n]))
}
In the next section, we'll explore the http package, which is built on top of the net package and provides a higher-level API for HTTP clients and servers.
By understanding these basic networking capabilities with the net package, you'll be well-equipped to build more complex network applications in Go.