echo_server.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package tests
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "os"
  7. "syscall"
  8. frpNet "github.com/fatedier/frp/utils/net"
  9. )
  10. func StartTcpEchoServer() {
  11. l, err := frpNet.ListenTcp("127.0.0.1", TEST_TCP_PORT)
  12. if err != nil {
  13. fmt.Printf("echo server listen error: %v\n", err)
  14. return
  15. }
  16. for {
  17. c, err := l.Accept()
  18. if err != nil {
  19. fmt.Printf("echo server accept error: %v\n", err)
  20. return
  21. }
  22. go echoWorker(c)
  23. }
  24. }
  25. func StartUdpEchoServer() {
  26. l, err := frpNet.ListenUDP("127.0.0.1", TEST_UDP_PORT)
  27. if err != nil {
  28. fmt.Printf("udp echo server listen error: %v\n", err)
  29. return
  30. }
  31. for {
  32. c, err := l.Accept()
  33. if err != nil {
  34. fmt.Printf("udp echo server accept error: %v\n", err)
  35. return
  36. }
  37. go echoWorker(c)
  38. }
  39. }
  40. func StartUnixDomainServer() {
  41. unixPath := TEST_UNIX_DOMAIN_ADDR
  42. os.Remove(unixPath)
  43. syscall.Umask(0)
  44. l, err := net.Listen("unix", unixPath)
  45. if err != nil {
  46. fmt.Printf("unix domain server listen error: %v\n", err)
  47. return
  48. }
  49. for {
  50. c, err := l.Accept()
  51. if err != nil {
  52. fmt.Printf("unix domain server accept error: %v\n", err)
  53. return
  54. }
  55. go echoWorker(c)
  56. }
  57. }
  58. func echoWorker(c net.Conn) {
  59. buf := make([]byte, 2048)
  60. for {
  61. n, err := c.Read(buf)
  62. if err != nil {
  63. if err == io.EOF {
  64. c.Close()
  65. break
  66. } else {
  67. fmt.Printf("echo server read error: %v\n", err)
  68. return
  69. }
  70. }
  71. c.Write(buf[:n])
  72. }
  73. }