kcp.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package net
  15. import (
  16. "fmt"
  17. "net"
  18. "github.com/fatedier/frp/utils/log"
  19. kcp "github.com/fatedier/kcp-go"
  20. )
  21. type KcpListener struct {
  22. net.Addr
  23. listener net.Listener
  24. accept chan Conn
  25. closeFlag bool
  26. log.Logger
  27. }
  28. func ListenKcp(bindAddr string, bindPort int) (l *KcpListener, err error) {
  29. listener, err := kcp.ListenWithOptions(fmt.Sprintf("%s:%d", bindAddr, bindPort), nil, 10, 3)
  30. if err != nil {
  31. return l, err
  32. }
  33. listener.SetReadBuffer(4194304)
  34. listener.SetWriteBuffer(4194304)
  35. l = &KcpListener{
  36. Addr: listener.Addr(),
  37. listener: listener,
  38. accept: make(chan Conn),
  39. closeFlag: false,
  40. Logger: log.NewPrefixLogger(""),
  41. }
  42. go func() {
  43. for {
  44. conn, err := listener.AcceptKCP()
  45. if err != nil {
  46. if l.closeFlag {
  47. close(l.accept)
  48. return
  49. }
  50. continue
  51. }
  52. conn.SetStreamMode(true)
  53. conn.SetWriteDelay(true)
  54. conn.SetNoDelay(1, 20, 2, 1)
  55. conn.SetMtu(1350)
  56. conn.SetWindowSize(1024, 1024)
  57. conn.SetACKNoDelay(false)
  58. l.accept <- WrapConn(conn)
  59. }
  60. }()
  61. return l, err
  62. }
  63. func (l *KcpListener) Accept() (Conn, error) {
  64. conn, ok := <-l.accept
  65. if !ok {
  66. return conn, fmt.Errorf("channel for kcp listener closed")
  67. }
  68. return conn, nil
  69. }
  70. func (l *KcpListener) Close() error {
  71. if !l.closeFlag {
  72. l.closeFlag = true
  73. l.listener.Close()
  74. }
  75. return nil
  76. }
  77. func NewKcpConnFromUdp(conn *net.UDPConn, connected bool, raddr string) (net.Conn, error) {
  78. kcpConn, err := kcp.NewConnEx(1, connected, raddr, nil, 10, 3, conn)
  79. if err != nil {
  80. return nil, err
  81. }
  82. kcpConn.SetStreamMode(true)
  83. kcpConn.SetWriteDelay(true)
  84. kcpConn.SetNoDelay(1, 20, 2, 1)
  85. kcpConn.SetMtu(1350)
  86. kcpConn.SetWindowSize(1024, 1024)
  87. kcpConn.SetACKNoDelay(false)
  88. return kcpConn, nil
  89. }