golang 并行转串行透明代理

前端之家收集整理的这篇文章主要介绍了golang 并行转串行透明代理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

放在这里做个备份


package main

import (
	"fmt"
	"log"
	"net"
)

const (
	realServer = "127.0.0.1:9002"
	selfPort   = 9010
)

type gameConn struct {
	ClientConn net.Conn
	PkgBuf     [maxPkgSize]byte
	PkgLen     int
	Channel    chan int
}

var gbChannel chan int
var connMap map[int](*gameConn)

func main() {
	// Listen on TCP port 2000 on all interfaces.
	ip := net.ParseIP("0.0.0.0")
	addr := net.TCPAddr{ip,selfPort}
	l,err := net.ListenTCP("tcp",&addr)
	if err != nil {
		log.Fatal(err)
	}

	serverConn,err := net.Dial("tcp",realServer)
	if err != nil {
		fmt.Println(err)
		return
	}

	log.Printf("starting server...")

	gbChannel = make(chan int)
	connMap = make(map[int](*gameConn))
	index := 0

	go redisProcess(serverConn)

	for {
		// Wait for a connection.
		conn,err := l.AcceptTCP()
		if err != nil {
			log.Fatal(err)
		}

		go start(conn,index)

		index++
	}
}


package main

import (
	"fmt"
	"net"
)

const (
	maxPkgSize = (4 * 1024 * 1024)
)

func start(netConn net.Conn,id int) {
	connInfo := new(gameConn)
	connInfo.ClientConn = netConn
	connInfo.Channel = make(chan int)

	connMap[id] = connInfo

	var err error
	connInfo.PkgLen,err = netConn.Read(connInfo.PkgBuf[:])
	if err != nil {
		fmt.Println(err)
		return
	} else if connInfo.PkgLen >= maxPkgSize {
		fmt.Printf("too long:%i\n",connInfo.PkgLen)
	} else {
		//		fmt.Printf("length:%i\n",length)
	}

	gbChannel <- id

	for {
		<-connInfo.Channel

		connInfo.PkgLen,err = netConn.Read(connInfo.PkgBuf[:])
		if err != nil {
			fmt.Println(err)
			return
		} else if connInfo.PkgLen >= maxPkgSize {
			fmt.Printf("too long:%i\n",connInfo.PkgLen)
		} else {
			//			fmt.Printf("length:%i\n",length)
		}

		gbChannel <- id
	}
}

func redisProcess(serverConn net.Conn) {
	var pGameConn *gameConn
	var id int
	for {
		id = <-gbChannel

		pGameConn = connMap[id]
		if pGameConn == nil {
			continue
		}

		length,err := serverConn.Write(pGameConn.PkgBuf[:pGameConn.PkgLen])
		if err != nil {
			fmt.Println(err)
			continue
		}

		length,err = serverConn.Read(pGameConn.PkgBuf[:])
		if err != nil {
			fmt.Println(err)
			continue
		} else if length >= maxPkgSize {
			fmt.Printf("too long:%i\n",length)
		} else {
			//		fmt.Printf("length:%i\n",length)
		}

		length,err = pGameConn.ClientConn.Write(pGameConn.PkgBuf[:length])
		if err != nil {
			fmt.Println(err)
			continue
		}

		pGameConn.Channel <- 1
	}

}
原文链接:https://www.f2er.com/go/191424.html

猜你在找的Go相关文章