【Golang】实现通过udp(kcp)转发tcp

179次阅读
没有评论

共计 1842 个字符,预计需要花费 5 分钟才能阅读完成。

通过客户端接受tcp请求,通过udp(kcp)转发到服务端,服务端通过udp(kcp)接受转发到真正的地址

主要通过kcp实现类似tcp的效果,通过go语言提供的io.copy方法,再tcp和udp之间拷贝

client 客户端代码:

package main

import (
  "fmt"
  "io"
  "log"
  "net"

  "github.com/xtaci/kcp-go"
)

const (
  //AppName = "GOXY"
  Version = "3.0.1"

  RecommendedBufferSize = 32 * 1024
)

//接受tcp请求,通过udp转发到服务端
func main() {
  listen, err := net.Listen("tcp", ":9897")
  if err != nil {
    log.Println(err)
  }
  defer listen.Close()
  for {
    conn, err := listen.Accept()
    if err != nil {
      log.Printf("conn error%v", err)
    }
    fmt.Println(conn.RemoteAddr(), conn.LocalAddr())
    //处理来自客户端的tcp请求
    kconn, err := kcp.DialWithOptions("localhost:30000", nil, 0, 0)
    kconn.SetStreamMode(true)
    kconn.SetWriteDelay(false)
    kconn.SetNoDelay(1, 10, 2, 1)
    kconn.SetWindowSize(1024, 1024)
    kconn.SetMtu(1400)
    kconn.SetACKNoDelay(false)
    kconn.SetDSCP(0)
    kconn.SetReadBuffer(4194304)
    kconn.SetReadBuffer(4194304)
    if err != nil {
      log.Panicln("udp dial error:", err)
      return
    }
    //defer kconn.Close()
    buff1, buff2 := make([]byte, RecommendedBufferSize), make([]byte, RecommendedBufferSize)
    go io.CopyBuffer(kconn, conn, buff1)
    go io.CopyBuffer(conn, kconn, buff2)
  }
}

 

server:

package main

import (
  "io"
  "log"
  "net"

  "github.com/xtaci/kcp-go"
)

const (
  Version = "3.0.1"
  RecommendedBufferSize = 32 * 1024
)

//转发udp到tcp
func main() {
  lis, err := kcp.ListenWithOptions(":30000", nil, 0, 0)
  if err != nil {
    panic(err)
  }
  lis.SetDSCP(0)
  lis.SetReadBuffer(4194304)
  lis.SetReadBuffer(4194304)

  // lis.SetReadBuffer(1024 * 1024 * 4)
  // lis.SetWriteBuffer(1024 * 1024 * 4)
  defer lis.Close()

  for {
    kconn, e := lis.AcceptKCP()
    if e != nil {
      panic(e)
    }
    log.Println("accepted:", kconn.RemoteAddr(), kconn.LocalAddr())
    kconn.SetStreamMode(true)
    kconn.SetWriteDelay(false)
    kconn.SetNoDelay(1, 10, 2, 1)
    kconn.SetMtu(1400)
    kconn.SetWindowSize(1024, 1024)
    kconn.SetACKNoDelay(false)
    dconn, err := net.Dial("tcp", "127.0.0.1:5201")
    if err != nil {
      panic(err)
    }
    defer dconn.Close()
    buff1, buff2 := make([]byte, RecommendedBufferSize), make([]byte, RecommendedBufferSize)
    go io.CopyBuffer(dconn, kconn, buff1)
    go io.CopyBuffer(kconn, dconn, buff2)
  }
}

 

正文完
 
admin
版权声明:本站原创文章,由 admin 2022-02-10发表,共计1842字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码