栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

GO tcp端口转发与映射

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

GO tcp端口转发与映射

TCP端口转发与映射核心代码:
本文章代码已用于生产环境,用来实现简单的负载均衡
github:https://github.com/lishuangquan1987/tcp_map

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"math/rand"
	"net"
	"os"
	"time"
)

type EndpointInfo struct {
	Ipstr string `json:"ipstr"`
}

type Config struct {
	Host    EndpointInfo   `json:"host"`
	MapList []EndpointInfo `json:"maplist"`
}

var config Config

func init() {
	f, err := os.Open("tcp_map.json")
	if err != nil {
		panic(err)
	}
	defer f.Close()
	bytes, err := ioutil.ReadAll(f)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(bytes, &config)
	if err != nil {
		panic(err)
	}
	//设置随机数种子
	rand.Seed(time.Now().UnixNano())
}

func main() {
	fmt.Println("welcome to tony tcp map!")
	fromaddr := config.Host.Ipstr
	fromlistener, err := net.Listen("tcp", fromaddr)

	if err != nil {
		log.Fatalf("Unable to listen on: %s, error: %sn", fromaddr, err.Error())
	}
	defer fromlistener.Close()

	tcpMap(fromlistener)

}

func tcpMap(listener net.Listener) {
	for {
		con, err := listener.Accept()
		if err != nil {
			panic(err)
		}
		//使用算法随机选取一个
		toIpStr := RandomSelect(config.MapList).Ipstr

		go func() {
			toCon, err := net.Dial("tcp", toIpStr)
			if err != nil {
				fmt.Printf("can not connect to %s", toIpStr)
				return
			}
			go handleConnection(con, toCon)
			go handleConnection(toCon, con)
		}()
	}
}

func RandomSelect(endPoints []EndpointInfo) EndpointInfo {
	index := rand.Intn(len(endPoints))
	return endPoints[index]
}

func handleConnection(r, w net.Conn) {
	defer r.Close()
	defer w.Close()

	var buffer = make([]byte, 100000)
	for {
		n, err := r.Read(buffer)
		if err != nil {
			break
		}

		n, err = w.Write(buffer[:n])
		if err != nil {
			break
		}
	}

}

配置文件tcp_map.json如下:

{
    
    "host":{
        "ipstr":"0.0.0.0:10002"
    },
    
    "maplist":[{
        "ipstr":"127.0.0.1:3306"
    },{
        "ipstr":"120.79.6.168:3306"
    }]
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/910429.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号