Networking with TCP and UDP sockets forms the backbone of communication between different devices over a network. In this chapter, we'll explore TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) sockets in Go, covering everything from basic socket programming to advanced techniques.
TCP and UDP are two of the most commonly used transport layer protocols in computer networks. TCP provides reliable, connection-oriented communication, while UDP offers lightweight, connectionless communication.
Socket programming involves creating endpoints for communication between two processes over a network. In Go, the net
package provides support for working with sockets.
TCP sockets provide reliable, stream-oriented communication between clients and servers.
package main
import (
"fmt"
"net"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error:", err)
return
}
defer ln.Close()
fmt.Println("TCP server listening on port 8080")
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println("Error:", err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
// Handle client connection
}
net.Listen()
.ln.Accept()
in a loop.UDP sockets provide connectionless, unreliable communication between clients and servers.
package main
import (
"fmt"
"net"
)
func main() {
addr, err := net.ResolveUDPAddr("udp", ":8080")
if err != nil {
fmt.Println("Error:", err)
return
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
fmt.Println("Error:", err)
return
}
defer conn.Close()
fmt.Println("UDP server listening on port 8080")
for {
buffer := make([]byte, 1024)
n, addr, err := conn.ReadFromUDP(buffer)
if err != nil {
fmt.Println("Error:", err)
continue
}
fmt.Printf("Received UDP message from %s: %s\n", addr, string(buffer[:n]))
}
}
net.ResolveUDPAddr()
and listen on port 8080 using net.ListenUDP()
.conn.ReadFromUDP()
in a loop and print them to the console.In this section, we’ll explore advanced socket programming techniques for TCP and UDP sockets in Go
Concurrent TCP servers use goroutines to handle multiple client connections concurrently.
package main
import (
"fmt"
"net"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error:", err)
return
}
defer ln.Close()
fmt.Println("Concurrent TCP server listening on port 8080")
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println("Error:", err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
// Handle client connection concurrently
}
Similar to the basic TCP server example, but we handle each client connection in a separate goroutine.
UDP clients send datagrams to UDP servers without establishing a connection.
package main
import (
"fmt"
"net"
)
func main() {
addr, err := net.ResolveUDPAddr("udp", "localhost:8080")
if err != nil {
fmt.Println("Error:", err)
return
}
conn, err := net.DialUDP("udp", nil, addr)
if err != nil {
fmt.Println("Error:", err)
return
}
defer conn.Close()
message := []byte("Hello, UDP server!")
_, err = conn.Write(message)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Message sent to UDP server")
}
net.ResolveUDPAddr()
and net.DialUDP()
.conn.Write()
.TCP and UDP sockets are essential for building networked applications in Go. By understanding the basic principles of socket programming and exploring advanced techniques, you can develop robust and scalable networked applications for various use cases. Experiment with different socket programming patterns, explore error handling strategies, and optimize performance to become proficient in TCP and UDP socket programming with Go. Happy coding !❤️