ZBLOG

golang dail tcp

To create a TCP server in Go, you can use the net package.

Here’s an example of creating a simple TCP server:

package main

import (
    "fmt"
    "net"
)

func main() {
    // listen on port 8080
    ln, err := net.Listen("tcp", ":8080")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer ln.Close()

    fmt.Println("TCP server listening on :8080")

    for {
        // wait for a connection
        conn, err := ln.Accept()
        if err != nil {
            fmt.Println(err)
            continue
        }

        // handle the connection in a separate goroutine
        go handleConnection(conn)
    }
}

func handleConnection(conn net.Conn) {
    defer conn.Close()

    // read from the connection
    buf := make([]byte, 1024)
    _, err := conn.Read(buf)
    if err != nil {
        fmt.Println(err)
        return
    }

    // echo back to the client
    conn.Write(buf)
}

In this example, we’re listening on port 8080 for incoming TCP connections. When a connection is accepted, we spawn a new goroutine to handle it. The handleConnection() function reads from the connection and echoes the data back to the client.

To test this server, you can use the telnet command:

$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hello, world!
hello, world!
Connection closed by foreign host.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=728

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?