Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Go Recipes for Developers

You're reading from   Go Recipes for Developers Top techniques and practical solutions for real-life Go programming problems

Arrow left icon
Product type Paperback
Published in Dec 2024
Publisher Packt
ISBN-13 9781835464397
Length 350 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Burak Serdar Burak Serdar
Author Profile Icon Burak Serdar
Burak Serdar
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Chapter 1: Project Organization 2. Chapter 2: Working with Strings FREE CHAPTER 3. Chapter 3: Working with Date and Time 4. Chapter 4: Working with Arrays, Slices, and Maps 5. Chapter 5: Working with Types, Structs, and Interfaces 6. Chapter 6: Working with Generics 7. Chapter 7: Concurrency 8. Chapter 8: Errors and Panics 9. Chapter 9: The Context Package 10. Chapter 10: Working with Large Data 11. Chapter 11: Working with JSON 12. Chapter 12: Processes 13. Chapter 13: Network Programming 14. Chapter 14: Streaming Input/Output 15. Chapter 15: Databases 16. Chapter 16: Logging 17. Chapter 17: Testing, Benchmarking, and Profiling 18. Index 19. Other Books You May Enjoy

Writing TCP clients

A TCP client connects to a TCP server that is listening on a port of some host. Once the connection is established, communication is bidirectional. In other words, the distinction between a server and a client is based on how the connection is established. When we say “server,” we mean the program that waits listening to a port, and when we say “client,” we mean the program that connects (“dials”) a port on a host that is being listened on by a server. Once the connection is established, both sides send and receive data asynchronously. TCP guarantees that the messages will be received in the order they are sent, and that the messages will not be lost, but there are no guarantees on when a message will be received by the other side.

How to do it...

  1. The client side has to know the server address and port. This should be provided by the environment (command line, configuration, etc.).
  2. Use net.Dial to create a connection to the server:
         conn, err := net.Dial("tcp", addr)
         if err != nil {
          // Handle error
         }
  3. Use the returned net.Conn object to send data to the server, or to receive data from the server:
       // Send a line of text
       text := []byte("Hello echo server!")
       conn.Write(text)
       // Read the response
       response := make([]byte, len(text))
       conn.Read(response)
       fmt.Println(string(response))
  4. Close the connection when done:
    conn.Close()

Here is the complete program:

var address = flag.String("a", ":8008", "Server address")
func main() {
     flag.Parse()
     conn, err := net.Dial("tcp", *address)
     if err != nil {
          panic(err)
     }
     // Send a line of text
     text := []byte("Hello echo server!")
     conn.Write(text)
     // Read the response
     response := make([]byte, len(text))
     conn.Read(response)
     fmt.Println(string(response))
     conn.Close()
}

This example demonstrates a request-response type of interaction with the server. This is not necessarily always the case. A network connection provides both an io.Writer and an io.Reader interface, and they can be used concurrently.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image