Home Backend Development Golang How to program with TCP in Go?

How to program with TCP in Go?

May 11, 2023 pm 03:57 PM
go programming tcp

Go language is a powerful programming language that provides numerous network programming libraries, including TCP/IP sockets. This article mainly introduces how to use Go language for TCP programming.

1. TCP/IP

TCP/IP is a protocol suite, which is the basis of network communication and the core protocol of the Internet. It is responsible for the transmission of data in the network. It includes two protocols, TCP and IP. TCP provides the reliability of datagram transmission, and IP is responsible for the forwarding of datagram transmission.

2. TCP Programming in Go

The net package in Go language provides related APIs for TCP programming, mainly including the following functions:

  1. net .DialTCP(): Create a TCP connection;
  2. net.ListenTCP(): Listen to a TCP port;
  3. net.TCPConn(): Represent a TCP connection.

Below we will introduce how to use these functions for TCP programming.

  1. Establishing a TCP connection

The client can use the net.DialTCP() function to establish a TCP connection to the server. The following is a sample code:

package main

import (
    "fmt"
    "net"
)

func main() {
    conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
        IP:   net.IPv4(127, 0, 0, 1),
        Port: 9999,
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    defer conn.Close()

    fmt.Println("Connected!")
}
Copy after login

In the above code, the first parameter of the DialTCP() function is the string "tcp" representing the network protocol type, and the second parameter is an address structure, using to the specified connection destination. Here we specify a connection to port 9999 on the local IP address 127.0.0.1. If the connection is successful, "Connected!" will be output.

  1. Listen on TCP port

The server can use the net.ListenTCP() function to listen on a specific TCP port. The following is a sample code:

package main

import (
    "fmt"
    "net"
)

func main() {
    tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
        IP:   net.IPv4(0, 0, 0, 0),
        Port: 9999,
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    defer tcpListener.Close()

    fmt.Println("Listening on port", 9999)
    for {
        conn, err := tcpListener.AcceptTCP()
        if err != nil {
            fmt.Println(err)
            continue
        }

        fmt.Println("New client connected.")
        go handleClient(conn)
    }
}

func handleClient(conn *net.TCPConn) {
    defer conn.Close()
    // TODO: 处理客户端请求
}
Copy after login

In the above code, the first parameter of the ListenTCP() function is the string "tcp" representing the network protocol type, and the second parameter is an address structure, using To specify the listening IP address and port number. Here we specify port 9999 to listen on all IP addresses. If the listening is successful, "Listening on port 9999" will be output.

Then, we call the AcceptTCP() function in an infinite loop to wait for the client to connect. When a client is connected, a new goroutine will be created to handle the client request, and "New client connected." will be output to the console.

  1. TCP connection processing

The code for processing TCP connections is often more complex. Generally speaking, we need to use the bufio.NewReader() function to read the client's request data, and then use the bufio.NewWriter() function to write the response data.

The following is a sample code for handling TCP connections:

func handleClient(conn *net.TCPConn) {
    defer conn.Close()

    // 读取客户端请求
    reader := bufio.NewReader(conn)
    req, err := reader.ReadString('
')
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Received request:", req)

    // 发送响应数据
    writer := bufio.NewWriter(conn)
    resp := "Hello, client!
"
    _, err = writer.WriteString(resp)
    if err != nil {
        fmt.Println(err)
        return
    }
    writer.Flush()
}
Copy after login

In the above code, we first create a bufio.NewReader() object to read the client request. After reading the data, we create a bufio.NewWriter() object to write the response data. Note that using the bufio.NewWriter() function to create a writer can cache output data and improve performance.

Finally, we use the WriteString() function to write the response data into the writer, and call the Flush() function to send the buffer data out.

3. Complete example

Finally, we demonstrate a complete TCP programming example, including client and server:

Server code:

package main

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

func main() {
    tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
        IP:   net.IPv4(0, 0, 0, 0),
        Port: 9999,
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    defer tcpListener.Close()

    fmt.Println("Listening on port", 9999)
    for {
        conn, err := tcpListener.AcceptTCP()
        if err != nil {
            fmt.Println(err)
            continue
        }

        fmt.Println("New client connected.")
        go handleClient(conn)
    }
}

func handleClient(conn *net.TCPConn) {
    defer conn.Close()

    // 读取客户端请求
    reader := bufio.NewReader(conn)
    req, err := reader.ReadString('
')
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Received request:", req)

    // 发送响应数据
    writer := bufio.NewWriter(conn)
    resp := "Hello, client!
"
    _, err = writer.WriteString(resp)
    if err != nil {
        fmt.Println(err)
        return
    }
    writer.Flush()
}
Copy after login

Client code:

package main

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

func main() {
    conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
        IP:   net.IPv4(127, 0, 0, 1),
        Port: 9999,
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    defer conn.Close()

    // 发送请求数据
    writer := bufio.NewWriter(conn)
    req := "Hello, server!
"
    _, err = writer.WriteString(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    writer.Flush()

    // 接收响应数据
    reader := bufio.NewReader(conn)
    resp, err := reader.ReadString('
')
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Received response:", resp)
}
Copy after login

In the above code, the server first listens to port 9999, and then waits for the client to connect. When the client connects, the server reads the client request and then sends response data.

The client first establishes a TCP connection to the server, and then sends request data to the server. After sending the request, the client waits to receive response data from the server.

4. Summary

This article introduces how to use Go language for TCP programming. We learned the basics of the TCP/IP protocol, and then introduced how to implement TCP programming in the Go language using the API provided by the net package. At the same time, this article provides a complete example, I hope it will be helpful to readers.

The above is the detailed content of How to program with TCP in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
How to send Go WebSocket messages? How to send Go WebSocket messages? Jun 03, 2024 pm 04:53 PM

In Go, WebSocket messages can be sent using the gorilla/websocket package. Specific steps: Establish a WebSocket connection. Send a text message: Call WriteMessage(websocket.TextMessage,[]byte("Message")). Send a binary message: call WriteMessage(websocket.BinaryMessage,[]byte{1,2,3}).

How to avoid memory leaks in Golang technical performance optimization? How to avoid memory leaks in Golang technical performance optimization? Jun 04, 2024 pm 12:27 PM

Memory leaks can cause Go program memory to continuously increase by: closing resources that are no longer in use, such as files, network connections, and database connections. Use weak references to prevent memory leaks and target objects for garbage collection when they are no longer strongly referenced. Using go coroutine, the coroutine stack memory will be automatically released when exiting to avoid memory leaks.

Things to note when Golang functions receive map parameters Things to note when Golang functions receive map parameters Jun 04, 2024 am 10:31 AM

When passing a map to a function in Go, a copy will be created by default, and modifications to the copy will not affect the original map. If you need to modify the original map, you can pass it through a pointer. Empty maps need to be handled with care, because they are technically nil pointers, and passing an empty map to a function that expects a non-empty map will cause an error.

How to use Golang's error wrapper? How to use Golang's error wrapper? Jun 03, 2024 pm 04:08 PM

In Golang, error wrappers allow you to create new errors by appending contextual information to the original error. This can be used to unify the types of errors thrown by different libraries or components, simplifying debugging and error handling. The steps are as follows: Use the errors.Wrap function to wrap the original errors into new errors. The new error contains contextual information from the original error. Use fmt.Printf to output wrapped errors, providing more context and actionability. When handling different types of errors, use the errors.Wrap function to unify the error types.

How to create a prioritized Goroutine in Go? How to create a prioritized Goroutine in Go? Jun 04, 2024 pm 12:41 PM

There are two steps to creating a priority Goroutine in the Go language: registering a custom Goroutine creation function (step 1) and specifying a priority value (step 2). In this way, you can create Goroutines with different priorities, optimize resource allocation and improve execution efficiency.

How to use gomega for assertions in Golang unit tests? How to use gomega for assertions in Golang unit tests? Jun 05, 2024 pm 10:48 PM

How to use Gomega for assertions in Golang unit testing In Golang unit testing, Gomega is a popular and powerful assertion library that provides rich assertion methods so that developers can easily verify test results. Install Gomegagoget-ugithub.com/onsi/gomega Using Gomega for assertions Here are some common examples of using Gomega for assertions: 1. Equality assertion import "github.com/onsi/gomega" funcTest_MyFunction(t*testing.T){

Unleash Your Inner Programmer: C for Absolute Beginners Unleash Your Inner Programmer: C for Absolute Beginners Oct 11, 2024 pm 03:50 PM

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

See all articles