Learn network programming functions in Go language and implement TCP/IP communication

WBOY
Release: 2023-07-30 16:55:57
Original
1344 people have browsed it

Learn the network programming functions in Go language and implement TCP/IP communication

Go language is an open source programming language with the characteristics of high efficiency and low latency, so it is widely used in the field of network programming. Through the network programming functions provided by the Go language, we can easily implement TCP/IP communication. This article will introduce how to learn the network programming functions in the Go language and implement TCP/IP communication.

The network programming functions in Go language mainly include functions in the net package and bufio package. Among them, the net package provides access to network sockets, while the bufio package provides buffer reading and writing functions. Through the collaborative work of these two packages, we can easily handle the sending and receiving of network data.

First, we need to import the net and bufio packages:

import (
    "net"
    "bufio"
)
Copy after login

Then, we can create a TCP server to receive the client's request and reply with a welcome message. The following is a simple sample code:

func main() {
    // 监听端口
    listen, err := net.Listen("tcp", "localhost:8080")
    if err != nil {
        log.Fatal(err)
    }
    defer listen.Close()

    // 接收客户端连接
    conn, err := listen.Accept()
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    // 创建缓冲区进行读写
    reader := bufio.NewReader(conn)
    writer := bufio.NewWriter(conn)

    // 读取客户端的请求
    request, err := reader.ReadString('
')
    if err != nil {
        log.Fatal(err)
    }

    // 回复客户端的请求
    response := "欢迎光临!
"
    _, err = writer.WriteString(response)
    if err != nil {
        log.Fatal(err)
    }

    // 刷新缓冲区,确保数据发送到客户端
    err = writer.Flush()
    if err != nil {
        log.Fatal(err)
    }
}
Copy after login

In the above example, we first create a listener using the net.Listen function, specifying the TCP protocol and port number. Then, receive the client's connection request by calling the listen.Accept function and create a socket connection for communicating with the client.

Next, we create bufio.Reader and bufio.Writer objects for reading and sending data from the socket connection. By calling the reader.ReadString function, you can read the request sent by the client, and by calling the writer.WriteString function, you can reply to the client's request.

Finally, we use the writer.Flush function to refresh the buffer to ensure that the data is sent to the client. After completing the above steps, we have successfully implemented a simple TCP server.

In addition to creating a TCP server, we can also create a TCP client, connect to the server and send requests. Here is a simple sample code:

func main() {
    // 连接服务器
    conn, err := net.Dial("tcp", "localhost:8080")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    // 创建缓冲区进行读写
    reader := bufio.NewReader(conn)
    writer := bufio.NewWriter(conn)
    
    // 发送请求
    request := "Hello, world!
"
    _, err = writer.WriteString(request)
    if err != nil {
        log.Fatal(err)
    }

    // 刷新缓冲区,确保数据发送到服务器
    err = writer.Flush()
    if err != nil {
        log.Fatal(err)
    }

    // 读取服务器的响应
    response, err := reader.ReadString('
')
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(response)
}
Copy after login

The above is the detailed content of Learn network programming functions in Go language and implement TCP/IP communication. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template