Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Creating a TCP Client in Go

Introduction

In this tutorial, we will learn how to create a TCP client using the Go programming language. A TCP client communicates with a TCP server by establishing a connection to a specified port and IP address, sending requests, and receiving responses. This is useful for applications that require reliable, ordered, and error-checked delivery of a stream of bytes.

Prerequisites

Before we start, ensure you have the following:

  • Go installed on your machine. You can download it from the official Go website.
  • A basic understanding of Go programming.
  • A code editor or IDE of your choice.

Setting Up the Project

First, let's set up a new Go project. Open your terminal and create a new directory for your project:

mkdir tcp-client cd tcp-client

Initialize a new Go module in the project directory:

go mod init tcp-client

Writing the TCP Client Code

Now, let's create a new file named main.go and write the TCP client code. Open your code editor and create the main.go file:

package main

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

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

    // Read input from the user
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')

    // Send the text to the server
    fmt.Fprintf(conn, text+"\n")

    // Receive the response from the server
    message, _ := bufio.NewReader(conn).ReadString('\n')
    fmt.Print("Message from server: " + message)
}
                

Explanation

Let's break down the code:

  • net.Dial("tcp", "localhost:8080"): This function establishes a connection to the TCP server running on localhost at port 8080. If the connection fails, it returns an error.
  • defer conn.Close(): This ensures that the connection is closed when the function returns.
  • bufio.NewReader(os.Stdin): This creates a new reader for reading input from the standard input (user input).
  • fmt.Fprintf(conn, text+"\n"): This sends the user input to the server.
  • bufio.NewReader(conn).ReadString('\n'): This reads the response from the server until a newline character is encountered.

Running the TCP Client

To run the TCP client, you need a TCP server running on localhost at port 8080. You can use a simple TCP server written in Go or any other language. For demonstration purposes, here is a simple Go TCP server:

package main

import (
    "bufio"
    "fmt"
    "net"
)

func main() {
    ln, _ := net.Listen("tcp", ":8080")
    conn, _ := ln.Accept()
    for {
        message, _ := bufio.NewReader(conn).ReadString('\n')
        fmt.Print("Message Received:", string(message))
        conn.Write([]byte(message + "\n"))
    }
}
                

Run the TCP server in one terminal:

go run server.go

In another terminal, run the TCP client:

go run main.go

Enter a message when prompted. The server will echo the message back to the client.

Conclusion

In this tutorial, you learned how to create a simple TCP client in Go. You established a connection to a TCP server, sent data, and received a response. This is a fundamental concept in networking that can be extended to create more complex client-server applications.