server.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "math/rand"
  7. "net"
  8. "os"
  9. "time"
  10. "github.com/cryptix/goremutake"
  11. "github.com/ftrvxmtrx/fd"
  12. )
  13. const path = "/tmp/sendMsgTest.sock"
  14. func main() {
  15. rand.Seed(time.Now().Unix())
  16. os.Remove(path)
  17. addr, err := net.ResolveUnixAddr("unix", path)
  18. check(err)
  19. l, err := net.ListenUnix("unix", addr)
  20. check(err)
  21. log.Println("Accepting unix sockets")
  22. done := make(chan struct{})
  23. errc := make(chan error)
  24. go func() {
  25. for {
  26. select {
  27. case e := <-errc:
  28. if e != nil {
  29. log.Printf("Error from errChan:\n%s\n", e)
  30. break
  31. }
  32. default:
  33. clientConn, err := l.AcceptUnix()
  34. if err != nil {
  35. log.Printf("AcceptUnix() error:%s\n", err)
  36. break
  37. }
  38. log.Println("Accepting Connection")
  39. go handleConn(clientConn, errc)
  40. }
  41. }
  42. close(done)
  43. }()
  44. <-done
  45. log.Println("Accept loop closed.")
  46. }
  47. func check(err error) {
  48. if err != nil {
  49. panic(err)
  50. }
  51. }
  52. func handleConn(c *net.UnixConn, errc chan error) {
  53. defer c.Close()
  54. fname := "/tmp/" + goremutake.Encode(uint(1024+rand.Intn(10000)))
  55. f, err := os.Create(fname)
  56. if err != nil {
  57. errc <- fmt.Errorf("Create rand file failed: %s", err)
  58. return
  59. }
  60. defer f.Close()
  61. err = fd.Put(c, f)
  62. if err != nil {
  63. errc <- fmt.Errorf("Create rand file failed: %s", err)
  64. return
  65. }
  66. log.Println("FD Send")
  67. time.Sleep(10 * time.Second)
  68. log.Println("timout.")
  69. go cleanupFile(fname)
  70. return
  71. }
  72. func cleanupFile(fname string) {
  73. time.Sleep(1 * time.Second)
  74. f, err := ioutil.ReadFile(fname)
  75. check(err)
  76. log.Printf("Content of File:%s\n", fname)
  77. log.Print(string(f))
  78. time.Sleep(1 * time.Second)
  79. log.Println("Removing file")
  80. os.Remove(fname)
  81. }