kcp.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. kcp "github.com/fatedier/kcp-go"
  19. )
  20. type KCPListener struct {
  21. listener net.Listener
  22. acceptCh chan net.Conn
  23. closeFlag bool
  24. }
  25. func ListenKcp(address string) (l *KCPListener, err error) {
  26. listener, err := kcp.ListenWithOptions(address, nil, 10, 3)
  27. if err != nil {
  28. return l, err
  29. }
  30. listener.SetReadBuffer(4194304)
  31. listener.SetWriteBuffer(4194304)
  32. l = &KCPListener{
  33. listener: listener,
  34. acceptCh: make(chan net.Conn),
  35. closeFlag: false,
  36. }
  37. go func() {
  38. for {
  39. conn, err := listener.AcceptKCP()
  40. if err != nil {
  41. if l.closeFlag {
  42. close(l.acceptCh)
  43. return
  44. }
  45. continue
  46. }
  47. conn.SetStreamMode(true)
  48. conn.SetWriteDelay(true)
  49. conn.SetNoDelay(1, 20, 2, 1)
  50. conn.SetMtu(1350)
  51. conn.SetWindowSize(1024, 1024)
  52. conn.SetACKNoDelay(false)
  53. l.acceptCh <- conn
  54. }
  55. }()
  56. return l, err
  57. }
  58. func (l *KCPListener) Accept() (net.Conn, error) {
  59. conn, ok := <-l.acceptCh
  60. if !ok {
  61. return conn, fmt.Errorf("channel for kcp listener closed")
  62. }
  63. return conn, nil
  64. }
  65. func (l *KCPListener) Close() error {
  66. if !l.closeFlag {
  67. l.closeFlag = true
  68. l.listener.Close()
  69. }
  70. return nil
  71. }
  72. func (l *KCPListener) Addr() net.Addr {
  73. return l.listener.Addr()
  74. }
  75. func NewKCPConnFromUDP(conn *net.UDPConn, connected bool, raddr string) (net.Conn, error) {
  76. kcpConn, err := kcp.NewConnEx(1, connected, raddr, nil, 10, 3, conn)
  77. if err != nil {
  78. return nil, err
  79. }
  80. kcpConn.SetStreamMode(true)
  81. kcpConn.SetWriteDelay(true)
  82. kcpConn.SetNoDelay(1, 20, 2, 1)
  83. kcpConn.SetMtu(1350)
  84. kcpConn.SetWindowSize(1024, 1024)
  85. kcpConn.SetACKNoDelay(false)
  86. return kcpConn, nil
  87. }