Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Go Lang - Networking

Network Programming in Go

Network programming in Go involves creating applications that communicate over the network using various protocols such as TCP, UDP, HTTP, and more. Go's standard library provides robust support for network operations, making it suitable for building servers, clients, and distributed systems.

Key Points:

  • Go's net package offers functionalities for TCP/IP, UDP, and HTTP networking.
  • Concurrency in Go, with goroutines and channels, enhances the performance and scalability of network applications.
  • Examples of network programming in Go include creating TCP servers, HTTP servers, and clients for various protocols.

Example of Networking in Go

Below is a basic example demonstrating how to create a simple TCP server in Go:


// Example: Networking in Go
package main

import (
    "fmt"
    "net"
)

func main() {
    // Listen for incoming connections on port 8080
    listener, err := net.Listen("tcp", ":8080")
    if err != nil {
        fmt.Println("Error listening:", err)
        return
    }
    defer listener.Close()

    fmt.Println("Server listening on port 8080...")

    // Accept connections and handle them concurrently
    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("Error accepting connection:", err)
            return
        }

        // Handle each connection in a new goroutine
        go handleConnection(conn)
    }
}

func handleConnection(conn net.Conn) {
    defer conn.Close()

    // Read data from the connection
    buffer := make([]byte, 1024)
    n, err := conn.Read(buffer)
    if err != nil {
        fmt.Println("Error reading:", err)
        return
    }

    // Print received message
    fmt.Printf("Received message: %s\n", string(buffer[:n]))

    // Respond to the client
    response := []byte("Message received!")
    _, err = conn.Write(response)
    if err != nil {
        fmt.Println("Error writing:", err)
        return
    }
}
          

Summary

This guide provided an overview of network programming in Go, demonstrating its capabilities with examples of creating a TCP server. By leveraging Go's standard library and concurrency features, developers can build efficient network applications that handle communication over various protocols.