~/Socket Programming in Golang

Mar 16, 2021


Socket programming in Golang allows direct network communication using TCP or UDP. The standard library net package provides the necessary tools.

Example: Simple TCP server.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
  "net"
  "fmt"
)

func main() {
  ln, err := net.Listen("tcp", ":8080")
  if err != nil {
    panic(err)
  }
  defer ln.Close()
  for {
    conn, err := ln.Accept()
    if err != nil {
      continue
    }
    go handleConnection(conn)
  }
}

func handleConnection(conn net.Conn) {
  defer conn.Close()
  buf := make([]byte, 1024)
  n, err := conn.Read(buf)
  if err == nil {
    conn.Write([]byte("Received: " + string(buf[:n])))
  }
}

Client example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
  "net"
  "fmt"
  "os"
)

func main() {
  conn, err := net.Dial("tcp", "localhost:8080")
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
  defer conn.Close()
  conn.Write([]byte("Hello server"))
  buf := make([]byte, 1024)
  n, _ := conn.Read(buf)
  fmt.Println(string(buf[:n]))
}

The net.Conn interface provides methods for reading and writing. Error handling is essential for robust network programming. For UDP, use net.ListenPacket instead.

For more, see the Go net package docs.

Tags: [golang] [sockets]