Viktor Ghorbali
2 min readFeb 24, 2023

Socket Programming in Go, Write a simple TCP client/server

Socket programming in golang

Socket programming is a fundamental aspect of network programming, allowing software to communicate over the internet. In Go, socket programming is made easy with its built-in support for TCP and UDP protocols. In this article, we’ll cover the basics of socket programming in Go, including how to create a server and a client.

Creating a TCP Server

To create a TCP server in Go, we first need to import the net package, which provides the necessary functions and types for socket programming. Here's an example of how to create a simple TCP server:

package main

import (
"fmt"
"net"
)

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

// Accept incoming connections and handle them
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
}

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

func handleConnection(conn net.Conn) {
// Close the connection when we're done
defer conn.Close()

// Read incoming data
buf := make([]byte, 1024)
_, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
return
}

// Print the incoming data
fmt.Printf("Received: %s", buf)
}

In this code, we first listen for incoming connections on port 8080 using the net.Listen function. Once a connection is established, we accept it using the ln.Accept method and handle it in a new goroutine using the handleConnection function.

The handleConnection function reads incoming data from the connection and prints it to the console. Finally, we close the connection when we're done.

Creating a TCP Client

To create a TCP client in Go, we can use the net.Dial function to establish a connection to a server. Here's an example:

package main

import (
"fmt"
"net"
)

func main() {
// Connect to the server
conn, err := net.Dial("tcp", "localhost:8080")
if err != nil {
fmt.Println(err)
return
}

// Send some data to the server
_, err = conn.Write([]byte("Hello, server!"))
if err != nil {
fmt.Println(err)
return
}

// Close the connection
conn.Close()
}

In this code, we first use the net.Dial function to connect to the server running on localhost at port 8080. Once the connection is established, we send some data to the server using the conn.Write method. Finally, we close the connection.

Conclusion

Socket programming is an important skill for network programming, and Go makes it easy with its built-in support for TCP and UDP protocols. In this article, we covered the basics of socket programming in Go, including how to create a server and a client. With these skills, you’ll be well on your way to building powerful network applications in Go.

Viktor Ghorbali

backend developer with experience in Go, DevOps, microservices, Linux, Python, and database design.