Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

1 snippets
  • Simple TCP client in Go

    package main
    
    import (
    	"bufio"
    	"fmt"
    	"net"
    	"time"
    )
    
    type Client struct {
    	conn net.Conn
    }
    
    func (c *Client) Write(content string) error {
    	_, err := c.conn.Write([]byte(content + "\n"))
    
    	return err
    }
    
    func (c *Client) Read() (string, error) {
    	reader := bufio.NewReader(c.conn)
    
    	return reader.ReadString('\n')
    }
    
    func (c *Client) Close() error {
    	return c.conn.Close()
    }
    
    // create tcp client
    func getClient(address string) (*Client, error) {
    	// try to resolve address
    	_, err := net.ResolveTCPAddr("tcp", address)
    
    	if err != nil {
    		return nil, err
    	}
    
    	// create tcp connection with 5s timeout 
    	conn, err := net.DialTimeout("tcp", address, 5*time.Second)
    
    	if err != nil {
    		return nil, err
    	}
    
    	conn.SetReadDeadline(time.Now().Add(5 * time.Second))
    	conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
    
    	return &Client{conn: conn}, nil
    }
    
    func main() {
    	// see https://tcpbin.com/
    	client, err := getClient("tcpbin.com:4242")
    
    	if err != nil {
    		panic(err)
    	}
    
    	// close the connection at the end
    	defer client.Close()
    
    	// send request to tcpbin.com echo server
    	err = client.Write("Hello, World!!!")
    
    	if err != nil {
    		panic(err)
    	}
    
    	// read response from tcpbin.com echo server
    	content, err := client.Read()
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Print(content)
    }
    
    // $ go run main.go 
    // Hello, World!!!

    This example should give a basic understanding of how to create a TCP client in Go.