zoukankan      html  css  js  c++  java
  • go网关

    package main
    
    import (
    	"flag"
    	"fmt"
    	"io"
    	"net"
    	"os"
    	"strings"
    	"sync"
    )
    
    var lock sync.Mutex
    var trueList []string
    var ip string
    var list string
    var javaApiHost string
    
    func main() {
    	fmt.Println("into func main")
    
    
    	//Package flag implements command-line flag parsing.
    	flag.StringVar(&ip, "l", ":9897", "-l=0.0.0.0:9897 指定服务监听的端口")
    	//flag.StringVar(&list, "d", "127.0.0.1:1789,127.0.0.1:1788", "-d=127.0.0.1:1789,127.0.0.1:1788 指定后端的IP和端口,多个用','隔开")
    	flag.StringVar(&list, "d", "1.2.3.4:8080", "-d=1.2.3.4:8080 指定后端的IP和端口,多个用','隔开")
    	flag.Parse()
    	trueList = strings.Split(list, ",")
    	fmt.Println(trueList)
    
    	if len(trueList) <= 0 {
    		fmt.Println("后端IP和端口不能空,或者无效")
    		os.Exit(1)
    	}
    	server()
    }
    
    func server() {
    	lis, err := net.Listen("tcp", ip)
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	defer lis.Close()
    	for {
    		conn, err := lis.Accept()
    		if err != nil {
    			fmt.Println("建立连接错误:%v
    ", err)
    			continue
    		}
    		fmt.Println(conn.RemoteAddr(), conn.LocalAddr())
    		go handle(conn)
    	}
    }
    
    func handle(sconn net.Conn) {
    	defer sconn.Close()
    	ip, ok := getIP()
    	if !ok {
    		return
    	}
    	dconn, err := net.Dial("tcp", ip)
    	if err != nil {
    		fmt.Printf("连接%v失败:%v
    ", ip, err)
    		return
    	}
    	ExitChan := make(chan bool, 1)
    	go func(sconn net.Conn, dconn net.Conn, Exit chan bool) {
    		_, err := io.Copy(dconn, sconn)
    		fmt.Printf("往%v发送数据失败:%v
    ", ip, err)
    		ExitChan <- true
    	}(sconn, dconn, ExitChan)
    	go func(sconn net.Conn, dconn net.Conn, Exit chan bool) {
    		_, err := io.Copy(sconn, dconn)
    		fmt.Printf("从%v接收数据失败:%v
    ", ip, err)
    		ExitChan <- true
    	}(sconn, dconn, ExitChan)
    	<-ExitChan
    	dconn.Close()
    }
    
    func getIP() (string, bool) {
    	lock.Lock()
    	defer lock.Unlock()
    
    	if len(trueList) < 1 {
    		return "", false
    	}
    	ip := trueList[0]
    	trueList = append(trueList[1:], ip)
    	return ip, true
    }
    

      golang 实现tcp转发代理 - Go语言中文网 - Golang中文社区 https://studygolang.com/articles/7261

  • 相关阅读:
    Mtk Ft6306 touch 驱动 .
    第一屏不显示懒加载的图片内容,这个方法可以搞定
    C#多线程中访问winform控件 (解决Winform 对象当前正在其他地方使用)
    变化的科技感十足的网站,推荐
    新年有感
    获取高精度时间注意事项 (QueryPerformanceCounter , QueryPerformanceFrequency)
    修改 TeamViewer ID 的方法
    VS2017离线安装包[百度云盘](收藏了)
    老子今天不加班,程序员也需要自由
    改变Eclipse 中代码字体大小
  • 原文地址:https://www.cnblogs.com/rsapaper/p/9485078.html
Copyright © 2011-2022 走看看