golang实现tcp端口转发示例代码

代码语言:golang

所属分类:其他

代码描述:golang实现tcp端口转发示例代码

代码标签: golang tcp 端口 转发 示例 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

package main

import (
    "io"
    "log"
    "net"
    "sync"
)

func main() {
    // 本地监听端口
    localPort := ":8888"
    // 目标服务器地址
    targetAddress := "127.0.0.1:3306"

    // 启动本地监听
    listener, err := net.Listen("tcp", localPort)
    if err != nil {
        log.Fatalf("Error starting local listener: %v", err)
    }
    defer listener.Close()
    log.Printf("Listening on %s and forwarding to %s\n", localPort, targetAddress)

    for {
        // 接受本地连接
        localConn, err := listener.Accept()
        if err != nil {
            log.Printf("Error accepting local connection: %v", err)
            continue
        }

        // 处理连接
        go handleConnection(localConn, targetAddress)
    }
}

func handleConnection(localConn net.Conn, targetAddress string) {
    defer localConn.Cl.........完整代码请登录后点击上方下载按钮下载查看

网友评论0